Threading

This module provides a PeriodicJob class for running a job periodically in the background.

Such jobs can be used e.g. to check for updates of the plugin, to detect changes in the plugin settings by a user, send heartbeats to a server or many other tasks that need to be done periodically.

See also

PeriodicJob for examples and usage.

class npc.PeriodicJob(update, delay=1, name='PeriodicJob', before_start=None)

Periodic job running as a daemon thread in the background

Note

  • The thread will always be started daemonized.

  • The thread will run the update function every delay seconds.

  • The thread can be paused and resumed.

  • The thread can be stopped.

Example

def update():
    now = datetime.now().strftime("%H:%M:%S")
    print(f"Hello World! {now}")

job = PeriodicJob(update, delay=2)
job.start()
# Hello World! 00:00:00
# Hello World! 00:00:02
# Hello World! 00:00:04
job.pause()
sleep(5)
job.resume()
# Hello World! 00:00:09
# Hello World! 00:00:11
job.stop()

Removed in version 0.5.0: npc.PeriodicJob.min_delay removed to make the waiting for next run non GIL blocking

Added in version 0.5.0: npc.PeriodicJob.all_jobs - list of all running jobs, npc.PeriodicJob.log - Logging for jobs, npc.PeriodicJob.id - Unique ID of the job, npc.PeriodicJob.set_log_level() - To change the log level for a job

Changed in version 0.5.0: _stopped -> _stop_event, _can_run -> _pause_event, npc.PeriodicJob.last_run - Is now a instance variable rather than class variable which could have caused unexpected behaviour

Parameters:
  • update (Callable) – Function to run every delay seconds

  • delay (int | Callable, optional) – Delay between updates in seconds as an integer or a function returning an integer

  • name (str, optional) – Name of the thread

  • before_start (Callable, optional) – Function to run before the thread starts

id

Unique ID of the job

Type:

str

log

Logger for the job

Type:

logging.Logger

update

Function to run every delay seconds

Type:

Callable

before_start

Function to run before the thread starts

Type:

Callable, optional

delay

Delay between updates in seconds

Type:

int | Callable

last_run

Time of the last update

Type:

float

all_jobs

List of all running jobs

Type:

list

set_log_level(level)

Set the log level for the job

Parameters:

level (str | int) – Log level as a string or integer

pause()

Pause the thread execution.

resume()

Resume the thread execution.

stop(wait=True)

Stop the thread gracefully.

Parameters:

wait (bool, optional) – Wait for the thread to stop

run()

Main loop for the thread.

Warning

Do not call this method directly, use threading.Thread.start() instead.