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_delayremoved to make the waiting for next run non GIL blockingAdded 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 jobChanged 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:
- log¶
Logger for the job
- Type:
- update¶
Function to run every delay seconds
- Type:
Callable
- before_start¶
Function to run before the thread starts
- Type:
Callable, optional
- set_log_level(level)¶
Set the log level for the job
- pause()¶
Pause the thread execution.
- resume()¶
Resume the thread execution.
- stop(wait=True)¶
Stop the thread gracefully.
- run()¶
Main loop for the thread.
Warning
Do not call this method directly, use
threading.Thread.start()instead.