Periodic task execution on a scheduler with weak reference callbacks.
This module provides :class:PeriodicTask which runs a callable repeatedly
at a fixed interval on a scheduler, with support for graceful start/stop,
error handling, and automatic cleanup when the callable is garbage collected.
PeriodicTask
Run a callable periodically on a scheduler.
The callable is held through a weak reference: once it gets garbage
collected the task stops rescheduling itself - so keep a reference to
the callable (or the object owning it) for as long as the task is meant
to run. Exceptions raised by the callable are logged and, by default,
stop the task.
Example
import time
import py_misc_utils.periodic_task as pt
import py_misc_utils.scheduler as sch
s = sch.Scheduler()
cnt = [0]
def tick():
cnt[0] += 1
task = pt.PeriodicTask('tick', tick, period=0.01, scheduler=s)
task.start()
time.sleep(0.05)
task.stop()
assert cnt[0] >= 1
Source code in py_misc_utils/periodic_task.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126 | class PeriodicTask:
"""Run a callable periodically on a scheduler.
The callable is held through a weak reference: once it gets garbage
collected the task stops rescheduling itself - so keep a reference to
the callable (or the object owning it) for as long as the task is meant
to run. Exceptions raised by the callable are logged and, by default,
stop the task.
Example:
import time
import py_misc_utils.periodic_task as pt
import py_misc_utils.scheduler as sch
s = sch.Scheduler()
cnt = [0]
def tick():
cnt[0] += 1
task = pt.PeriodicTask('tick', tick, period=0.01, scheduler=s)
task.start()
time.sleep(0.05)
task.stop()
assert cnt[0] >= 1
"""
def __init__(self, name, periodic_fn, period, scheduler=None, stop_on_error=None):
"""Initialize a PeriodicTask.
Args:
name: Human-readable name for the task.
periodic_fn: The callable to run periodically.
period: Interval in seconds between runs.
scheduler: Optional scheduler instance; defaults to the common scheduler.
stop_on_error: If True (default), stop the task when periodic_fn raises
an exception. If False, continue running despite errors.
"""
self._name = name
self._periodic_fn = wcall.WeakCall(periodic_fn)
self._period = period
self._scheduler = scheduler or sch.common_scheduler()
self._stop_on_error = stop_on_error in (None, True)
self._lock = threading.Lock()
self._event = None
self._completed_event = None
def start(self):
"""Schedule the first run of the periodic task.
Returns:
The PeriodicTask instance for chaining.
"""
with self._lock:
if self._event is None:
self._schedule()
return self
def stop(self):
"""Stop the periodic task and wait for any in-flight run to complete.
If the task is not running, this is a no-op.
Example:
import py_misc_utils.periodic_task as pt
import py_misc_utils.scheduler as sch
s = sch.Scheduler()
task = pt.PeriodicTask('tick', lambda: None, period=1.0, scheduler=s)
task.start()
task.stop() # Cancels the pending event and joins the in-flight run.
"""
completed_event = None
with self._lock:
if self._event is not None:
# If "events" is empty, we were not able to cancel the task, so it will be
# in flight, and we need to wait for it to complete before exiting.
events = self._scheduler.cancel(self._event)
completed_event = self._completed_event if not events else None
self._event = None
if completed_event is not None:
completed_event.wait()
def _schedule(self):
"""Enter the runner into the scheduler for the next period."""
self._event = self._scheduler.enter(self._period, self._runner)
self._completed_event = threading.Event()
def _runner(self):
"""Execute the periodic function and reschedule if appropriate.
Signals completion via _completed_event. If the callable has been garbage
collected (WeakCall returns GONE) or stop_on_error is set after an
exception, the task is not rescheduled.
"""
re_issue = True
try:
if self._periodic_fn() is wcall.GONE:
re_issue = False
except Exception as ex: # noqa: BLE001 -- policy boundary: stop_on_error must see any fn failure to decide re-issue vs stop
alog.exception(ex, exmsg=f'Exception while running periodic task "{self._name}"')
re_issue = not self._stop_on_error
finally:
with self._lock:
self._completed_event.set()
if self._event is not None:
if re_issue:
self._schedule()
else:
self._event = None
|
start()
Schedule the first run of the periodic task.
Returns:
| Type |
Description |
|
|
The PeriodicTask instance for chaining.
|
Source code in py_misc_utils/periodic_task.py
62
63
64
65
66
67
68
69
70
71
72 | def start(self):
"""Schedule the first run of the periodic task.
Returns:
The PeriodicTask instance for chaining.
"""
with self._lock:
if self._event is None:
self._schedule()
return self
|
stop()
Stop the periodic task and wait for any in-flight run to complete.
If the task is not running, this is a no-op.
Example
import py_misc_utils.periodic_task as pt
import py_misc_utils.scheduler as sch
s = sch.Scheduler()
task = pt.PeriodicTask('tick', lambda: None, period=1.0, scheduler=s)
task.start()
task.stop() # Cancels the pending event and joins the in-flight run.
Source code in py_misc_utils/periodic_task.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98 | def stop(self):
"""Stop the periodic task and wait for any in-flight run to complete.
If the task is not running, this is a no-op.
Example:
import py_misc_utils.periodic_task as pt
import py_misc_utils.scheduler as sch
s = sch.Scheduler()
task = pt.PeriodicTask('tick', lambda: None, period=1.0, scheduler=s)
task.start()
task.stop() # Cancels the pending event and joins the in-flight run.
"""
completed_event = None
with self._lock:
if self._event is not None:
# If "events" is empty, we were not able to cancel the task, so it will be
# in flight, and we need to wait for it to complete before exiting.
events = self._scheduler.cancel(self._event)
completed_event = self._completed_event if not events else None
self._event = None
if completed_event is not None:
completed_event.wait()
|