tgext.scheduler 2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import atexit
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from tgext.scheduler import scheduler
|
|
7
|
+
|
|
8
|
+
log = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
TGSHELL_MESSAGE = (
|
|
11
|
+
"tgext.scheduler was not started because the code is running inside a "
|
|
12
|
+
"tgshell session (TG_TGSHELL is set). If you need the scheduler here, "
|
|
13
|
+
"start it manually by calling tgext.scheduler.scheduler._start_scheduler()."
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def start_scheduler():
|
|
18
|
+
if os.environ.get("TG_TGSHELL"):
|
|
19
|
+
log.warning(TGSHELL_MESSAGE)
|
|
20
|
+
print(TGSHELL_MESSAGE, file=sys.stderr)
|
|
21
|
+
return
|
|
22
|
+
log.debug("Starting Scheduler")
|
|
23
|
+
scheduler._start_scheduler()
|
|
24
|
+
atexit.register(stop_scheduler)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def stop_scheduler():
|
|
28
|
+
log.debug("Shutting down scheduler")
|
|
29
|
+
scheduler._stop_scheduler()
|
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
"""Module that provides a cron-like task scheduler.
|
|
2
|
+
|
|
3
|
+
This task scheduler is designed to be used from inside your own program.
|
|
4
|
+
You can schedule Python functions to be called at specific intervals or
|
|
5
|
+
days. It uses the standard 'sched' module for the actual task scheduling,
|
|
6
|
+
but provides much more:
|
|
7
|
+
|
|
8
|
+
* repeated tasks (at intervals, or on specific days)
|
|
9
|
+
* error handling (exceptions in tasks don't kill the scheduler)
|
|
10
|
+
* optional to run scheduler in its own thread or separate process
|
|
11
|
+
* optional to run a task in its own thread or separate process
|
|
12
|
+
|
|
13
|
+
If the threading module is available, you can use the various Threaded
|
|
14
|
+
variants of the scheduler and associated tasks. If threading is not
|
|
15
|
+
available, you could still use the forked variants. If fork is also
|
|
16
|
+
not available, all processing is done in a single process, sequentially.
|
|
17
|
+
|
|
18
|
+
There are three Scheduler classes:
|
|
19
|
+
|
|
20
|
+
Scheduler ThreadedScheduler ForkedScheduler
|
|
21
|
+
|
|
22
|
+
You usually add new tasks to a scheduler using the add_interval_task or
|
|
23
|
+
add_daytime_task methods, with the appropriate processmethod argument
|
|
24
|
+
to select sequential, threaded or forked processing. NOTE: it is impossible
|
|
25
|
+
to add new tasks to a ForkedScheduler, after the scheduler has been started!
|
|
26
|
+
For more control you can use one of the following Task classes
|
|
27
|
+
and use schedule_task or schedule_task_abs:
|
|
28
|
+
|
|
29
|
+
IntervalTask ThreadedIntervalTask ForkedIntervalTask
|
|
30
|
+
SingleTask ThreadedSingleTask ForkedSingleTask
|
|
31
|
+
WeekdayTask ThreadedWeekdayTask ForkedWeekdayTask
|
|
32
|
+
MonthdayTask ThreadedMonthdayTask ForkedMonthdayTask
|
|
33
|
+
|
|
34
|
+
Kronos is the Greek God of Time.
|
|
35
|
+
|
|
36
|
+
This module is based on Kronos by Irmen de Jong, but has been modified
|
|
37
|
+
to better fit within TurboGears. Additionally, this module appeared to
|
|
38
|
+
no longer be supported/in development.
|
|
39
|
+
|
|
40
|
+
"""
|
|
41
|
+
#
|
|
42
|
+
# $Id: kronos.py,v 1.5 2004/10/06 22:43:49 irmen Exp $
|
|
43
|
+
#
|
|
44
|
+
# (c) Irmen de Jong.
|
|
45
|
+
# This is open-source software, released under the MIT Software License:
|
|
46
|
+
# http://www.opensource.org/licenses/mit-license.php
|
|
47
|
+
#
|
|
48
|
+
|
|
49
|
+
__all__ = [
|
|
50
|
+
"DayTaskRescheduler",
|
|
51
|
+
"ForkedIntervalTask",
|
|
52
|
+
"ForkedMonthdayTask",
|
|
53
|
+
"ForkedScheduler",
|
|
54
|
+
"ForkedSingleTask",
|
|
55
|
+
"ForkedTaskMixin",
|
|
56
|
+
"ForkedWeekdayTask",
|
|
57
|
+
"IntervalTask",
|
|
58
|
+
"MonthdayTask",
|
|
59
|
+
"Scheduler",
|
|
60
|
+
"SingleTask",
|
|
61
|
+
"Task",
|
|
62
|
+
"ThreadedIntervalTask",
|
|
63
|
+
"ThreadedMonthdayTask",
|
|
64
|
+
"ThreadedScheduler",
|
|
65
|
+
"ThreadedSingleTask",
|
|
66
|
+
"ThreadedTaskMixin",
|
|
67
|
+
"ThreadedWeekdayTask",
|
|
68
|
+
"WeekdayTask",
|
|
69
|
+
"add_interval_task",
|
|
70
|
+
"add_monthday_task",
|
|
71
|
+
"add_single_task",
|
|
72
|
+
"add_weekday_task",
|
|
73
|
+
"cancel",
|
|
74
|
+
"method",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
import logging
|
|
78
|
+
import os
|
|
79
|
+
import sched
|
|
80
|
+
import threading
|
|
81
|
+
import time
|
|
82
|
+
import weakref
|
|
83
|
+
from contextlib import suppress
|
|
84
|
+
|
|
85
|
+
from .util import Method
|
|
86
|
+
|
|
87
|
+
log = logging.getLogger(__name__)
|
|
88
|
+
|
|
89
|
+
method = Method
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Scheduler:
|
|
93
|
+
"""The Scheduler itself."""
|
|
94
|
+
|
|
95
|
+
def __init__(self):
|
|
96
|
+
self.running = True
|
|
97
|
+
self.sched = sched.scheduler(time.time, self.__delayfunc)
|
|
98
|
+
|
|
99
|
+
def __delayfunc(self, delay):
|
|
100
|
+
# This delay function is basically a time.sleep() that is
|
|
101
|
+
# divided up, so that we can check the self.running flag while delaying.
|
|
102
|
+
# there is an additional check in here to ensure that the top item of
|
|
103
|
+
# the queue hasn't changed
|
|
104
|
+
if delay < 10:
|
|
105
|
+
time.sleep(delay)
|
|
106
|
+
else:
|
|
107
|
+
toptime = self.sched.queue[0][0]
|
|
108
|
+
endtime = time.time() + delay
|
|
109
|
+
period = 5
|
|
110
|
+
stoptime = endtime - period
|
|
111
|
+
while (
|
|
112
|
+
self.running
|
|
113
|
+
and stoptime > time.time()
|
|
114
|
+
and self.sched.queue[0][0] == toptime
|
|
115
|
+
):
|
|
116
|
+
time.sleep(period)
|
|
117
|
+
if not self.running or self.sched.queue[0][0] != toptime:
|
|
118
|
+
return
|
|
119
|
+
now = time.time()
|
|
120
|
+
if endtime > now:
|
|
121
|
+
time.sleep(endtime - now)
|
|
122
|
+
|
|
123
|
+
def _acquire_lock(self):
|
|
124
|
+
pass
|
|
125
|
+
|
|
126
|
+
def _release_lock(self):
|
|
127
|
+
pass
|
|
128
|
+
|
|
129
|
+
def add_interval_task(
|
|
130
|
+
self, action, taskname, initialdelay, interval, processmethod, args, kw
|
|
131
|
+
):
|
|
132
|
+
"""Add a new Interval Task to the schedule.
|
|
133
|
+
|
|
134
|
+
A very short initialdelay or one of zero cannot be honored, you will
|
|
135
|
+
see a slight delay before the task is first executed. This is because
|
|
136
|
+
the scheduler needs to pick it up in its loop.
|
|
137
|
+
|
|
138
|
+
"""
|
|
139
|
+
if initialdelay < 0 or interval < 1:
|
|
140
|
+
raise ValueError("Delay or interval must be >0")
|
|
141
|
+
# Select the correct IntervalTask class. Not all types may be available!
|
|
142
|
+
if processmethod == method.sequential:
|
|
143
|
+
TaskClass = IntervalTask
|
|
144
|
+
elif processmethod == method.threaded:
|
|
145
|
+
TaskClass = ThreadedIntervalTask
|
|
146
|
+
elif processmethod == method.forked:
|
|
147
|
+
TaskClass = ForkedIntervalTask
|
|
148
|
+
else:
|
|
149
|
+
raise ValueError("Invalid processmethod")
|
|
150
|
+
if not args:
|
|
151
|
+
args = []
|
|
152
|
+
if not kw:
|
|
153
|
+
kw = {}
|
|
154
|
+
task = TaskClass(taskname, interval, action, args, kw)
|
|
155
|
+
self.schedule_task(task, initialdelay)
|
|
156
|
+
return task
|
|
157
|
+
|
|
158
|
+
def add_single_task(self, action, taskname, initialdelay, processmethod, args, kw):
|
|
159
|
+
"""Add a new task to the scheduler that will only be executed once."""
|
|
160
|
+
if initialdelay < 0:
|
|
161
|
+
raise ValueError("Delay must be >0")
|
|
162
|
+
# Select the correct SingleTask class. Not all types may be available!
|
|
163
|
+
if processmethod == method.sequential:
|
|
164
|
+
TaskClass = SingleTask
|
|
165
|
+
elif processmethod == method.threaded:
|
|
166
|
+
TaskClass = ThreadedSingleTask
|
|
167
|
+
elif processmethod == method.forked:
|
|
168
|
+
TaskClass = ForkedSingleTask
|
|
169
|
+
else:
|
|
170
|
+
raise ValueError("Invalid processmethod")
|
|
171
|
+
if not args:
|
|
172
|
+
args = []
|
|
173
|
+
if not kw:
|
|
174
|
+
kw = {}
|
|
175
|
+
task = TaskClass(taskname, action, args, kw)
|
|
176
|
+
self.schedule_task(task, initialdelay)
|
|
177
|
+
return task
|
|
178
|
+
|
|
179
|
+
def add_daytime_task(
|
|
180
|
+
self, action, taskname, weekdays, monthdays, timeonday, processmethod, args, kw
|
|
181
|
+
):
|
|
182
|
+
"""Add a new Day Task (Weekday or Monthday) to the schedule."""
|
|
183
|
+
if weekdays and monthdays:
|
|
184
|
+
raise ValueError("You can only specify weekdays or monthdays, not both")
|
|
185
|
+
if not args:
|
|
186
|
+
args = []
|
|
187
|
+
if not kw:
|
|
188
|
+
kw = {}
|
|
189
|
+
if weekdays:
|
|
190
|
+
# Select the correct WeekdayTask class.
|
|
191
|
+
# Not all types may be available!
|
|
192
|
+
if processmethod == method.sequential:
|
|
193
|
+
TaskClass = WeekdayTask
|
|
194
|
+
elif processmethod == method.threaded:
|
|
195
|
+
TaskClass = ThreadedWeekdayTask
|
|
196
|
+
elif processmethod == method.forked:
|
|
197
|
+
TaskClass = ForkedWeekdayTask
|
|
198
|
+
else:
|
|
199
|
+
raise ValueError("Invalid processmethod")
|
|
200
|
+
task = TaskClass(taskname, weekdays, timeonday, action, args, kw)
|
|
201
|
+
if monthdays:
|
|
202
|
+
# Select the correct MonthdayTask class.
|
|
203
|
+
# Not all types may be available!
|
|
204
|
+
if processmethod == method.sequential:
|
|
205
|
+
TaskClass = MonthdayTask
|
|
206
|
+
elif processmethod == method.threaded:
|
|
207
|
+
TaskClass = ThreadedMonthdayTask
|
|
208
|
+
elif processmethod == method.forked:
|
|
209
|
+
TaskClass = ForkedMonthdayTask
|
|
210
|
+
else:
|
|
211
|
+
raise ValueError("Invalid processmethod")
|
|
212
|
+
task = TaskClass(taskname, monthdays, timeonday, action, args, kw)
|
|
213
|
+
firsttime = task.get_schedule_time(True)
|
|
214
|
+
self.schedule_task_abs(task, firsttime)
|
|
215
|
+
return task
|
|
216
|
+
|
|
217
|
+
def schedule_task(self, task, delay):
|
|
218
|
+
"""Add a new task to the scheduler with the given delay (seconds).
|
|
219
|
+
|
|
220
|
+
Low-level method for internal use.
|
|
221
|
+
|
|
222
|
+
"""
|
|
223
|
+
if self.running:
|
|
224
|
+
# lock the sched queue, if needed
|
|
225
|
+
self._acquire_lock()
|
|
226
|
+
try:
|
|
227
|
+
task.event = self.sched.enter(delay, 0, task, (weakref.ref(self),))
|
|
228
|
+
finally:
|
|
229
|
+
self._release_lock()
|
|
230
|
+
else:
|
|
231
|
+
task.event = self.sched.enter(delay, 0, task, (weakref.ref(self),))
|
|
232
|
+
|
|
233
|
+
def schedule_task_abs(self, task, abstime):
|
|
234
|
+
"""Add a new task to the scheduler for the given absolute time value.
|
|
235
|
+
|
|
236
|
+
Low-level method for internal use.
|
|
237
|
+
|
|
238
|
+
"""
|
|
239
|
+
if self.running:
|
|
240
|
+
# lock the sched queue, if needed
|
|
241
|
+
self._acquire_lock()
|
|
242
|
+
try:
|
|
243
|
+
task.event = self.sched.enterabs(abstime, 0, task, (weakref.ref(self),))
|
|
244
|
+
finally:
|
|
245
|
+
self._release_lock()
|
|
246
|
+
else:
|
|
247
|
+
task.event = self.sched.enterabs(abstime, 0, task, (weakref.ref(self),))
|
|
248
|
+
|
|
249
|
+
def start(self):
|
|
250
|
+
"""Start the scheduler."""
|
|
251
|
+
self._run()
|
|
252
|
+
|
|
253
|
+
def stop(self):
|
|
254
|
+
"""Remove all pending tasks and stop the Scheduler."""
|
|
255
|
+
self.running = False
|
|
256
|
+
# On Python 3.12+ sched.scheduler.queue is a property returning a
|
|
257
|
+
# copy, so mutating it in place is a no-op. Cancel each pending
|
|
258
|
+
# event explicitly instead; ignore events that are already gone.
|
|
259
|
+
for event in list(self.sched.queue):
|
|
260
|
+
with suppress(ValueError):
|
|
261
|
+
self.sched.cancel(event)
|
|
262
|
+
|
|
263
|
+
def cancel(self, task):
|
|
264
|
+
"""Cancel given scheduled task."""
|
|
265
|
+
self.sched.cancel(task.event)
|
|
266
|
+
|
|
267
|
+
def _run(self):
|
|
268
|
+
# Low-level run method to do the actual scheduling loop.
|
|
269
|
+
while self.running:
|
|
270
|
+
try:
|
|
271
|
+
self.sched.run()
|
|
272
|
+
except Exception as exc:
|
|
273
|
+
log.exception("ERROR DURING SCHEDULER EXECUTION: %r", exc)
|
|
274
|
+
# queue is empty; sleep a short while before checking again
|
|
275
|
+
if self.running:
|
|
276
|
+
time.sleep(5)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class Task:
|
|
280
|
+
"""Abstract base class of all scheduler tasks"""
|
|
281
|
+
|
|
282
|
+
def __init__(self, name, action, args, kw):
|
|
283
|
+
"""This is an abstract class!"""
|
|
284
|
+
self.name = name
|
|
285
|
+
self.action = action
|
|
286
|
+
self.args = args
|
|
287
|
+
self.kw = kw
|
|
288
|
+
|
|
289
|
+
def __call__(self, schedulerref):
|
|
290
|
+
"""Execute the task action in the scheduler's thread."""
|
|
291
|
+
try:
|
|
292
|
+
self.execute()
|
|
293
|
+
except Exception as x:
|
|
294
|
+
self.handle_exception(x)
|
|
295
|
+
self.reschedule(schedulerref())
|
|
296
|
+
|
|
297
|
+
def reschedule(self, scheduler):
|
|
298
|
+
"""This method should be defined in one of the sub classes!"""
|
|
299
|
+
raise NotImplementedError(
|
|
300
|
+
"You're using the abstract base class 'Task', use a concrete class instead"
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
def execute(self):
|
|
304
|
+
"""Execute the actual task."""
|
|
305
|
+
self.action(*self.args, **self.kw)
|
|
306
|
+
|
|
307
|
+
def handle_exception(self, exc):
|
|
308
|
+
"""Handle any exception that occured during task execution."""
|
|
309
|
+
log.exception("ERROR DURING TASK EXECUTION: %r", exc)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class SingleTask(Task):
|
|
313
|
+
"""A task that only runs once."""
|
|
314
|
+
|
|
315
|
+
def reschedule(self, scheduler):
|
|
316
|
+
pass
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
class IntervalTask(Task):
|
|
320
|
+
"""A repeated task that occurs at certain intervals (in seconds)."""
|
|
321
|
+
|
|
322
|
+
def __init__(self, name, interval, action, args=None, kw=None):
|
|
323
|
+
Task.__init__(self, name, action, args, kw)
|
|
324
|
+
self.interval = interval
|
|
325
|
+
|
|
326
|
+
def reschedule(self, scheduler):
|
|
327
|
+
"""Reschedule this task according to its interval (in seconds)."""
|
|
328
|
+
scheduler.schedule_task(self, self.interval)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
class DayTaskRescheduler:
|
|
332
|
+
"""A mixin class that contains the reschedule logic for the DayTasks."""
|
|
333
|
+
|
|
334
|
+
def __init__(self, timeonday):
|
|
335
|
+
self.timeonday = timeonday
|
|
336
|
+
|
|
337
|
+
def get_schedule_time(self, today):
|
|
338
|
+
"""Calculate the time value at which this task is to be scheduled."""
|
|
339
|
+
now = list(time.localtime())
|
|
340
|
+
if today:
|
|
341
|
+
# schedule for today. let's see if that is still possible
|
|
342
|
+
if (now[3], now[4]) >= self.timeonday:
|
|
343
|
+
# too bad, it will be tomorrow
|
|
344
|
+
now[2] += 1
|
|
345
|
+
else:
|
|
346
|
+
# tomorrow
|
|
347
|
+
now[2] += 1
|
|
348
|
+
# set new time on day (hour,minute)
|
|
349
|
+
now[3], now[4] = self.timeonday
|
|
350
|
+
# seconds
|
|
351
|
+
now[5] = 0
|
|
352
|
+
return time.mktime(tuple(now))
|
|
353
|
+
|
|
354
|
+
def reschedule(self, scheduler):
|
|
355
|
+
"""Reschedule this task according to the daytime for the task.
|
|
356
|
+
|
|
357
|
+
The task is scheduled for tomorrow, for the given daytime.
|
|
358
|
+
|
|
359
|
+
"""
|
|
360
|
+
# (The execute method in the concrete Task classes will check
|
|
361
|
+
# if the current day is a day on which the task must run).
|
|
362
|
+
abstime = self.get_schedule_time(False)
|
|
363
|
+
scheduler.schedule_task_abs(self, abstime)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class WeekdayTask(DayTaskRescheduler, Task):
|
|
367
|
+
"""A task that is called at specific days in a week (1-7), at a fixed time
|
|
368
|
+
on the day.
|
|
369
|
+
|
|
370
|
+
"""
|
|
371
|
+
|
|
372
|
+
def __init__(self, name, weekdays, timeonday, action, args=None, kw=None):
|
|
373
|
+
if not isinstance(timeonday, (list, tuple)) or len(timeonday) != 2:
|
|
374
|
+
raise TypeError("timeonday must be a 2-tuple (hour,minute)")
|
|
375
|
+
if not isinstance(weekdays, (list, tuple)):
|
|
376
|
+
raise TypeError(
|
|
377
|
+
"weekdays must be a sequence of weekday numbers 1-7 (1 is Monday)"
|
|
378
|
+
)
|
|
379
|
+
DayTaskRescheduler.__init__(self, timeonday)
|
|
380
|
+
Task.__init__(self, name, action, args, kw)
|
|
381
|
+
self.days = weekdays
|
|
382
|
+
|
|
383
|
+
def execute(self):
|
|
384
|
+
# This is called every day, at the correct time. We only need to
|
|
385
|
+
# check if we should run this task today (this day of the week).
|
|
386
|
+
weekday = time.localtime().tm_wday + 1
|
|
387
|
+
if weekday in self.days:
|
|
388
|
+
self.action(*self.args, **self.kw)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class MonthdayTask(DayTaskRescheduler, Task):
|
|
392
|
+
"""A task that is called at specific days in a month (1-31), at a fixed
|
|
393
|
+
time on the day.
|
|
394
|
+
|
|
395
|
+
"""
|
|
396
|
+
|
|
397
|
+
def __init__(self, name, monthdays, timeonday, action, args=None, kw=None):
|
|
398
|
+
if not isinstance(timeonday, (list, tuple)) or len(timeonday) != 2:
|
|
399
|
+
raise TypeError("timeonday must be a 2-tuple (hour,minute)")
|
|
400
|
+
if not isinstance(monthdays, (list, tuple)):
|
|
401
|
+
raise TypeError("monthdays must be a sequence of monthdays numbers 1-31")
|
|
402
|
+
DayTaskRescheduler.__init__(self, timeonday)
|
|
403
|
+
Task.__init__(self, name, action, args, kw)
|
|
404
|
+
self.days = monthdays
|
|
405
|
+
|
|
406
|
+
def execute(self):
|
|
407
|
+
# This is called every day, at the correct time. We only need to
|
|
408
|
+
# check if we should run this task today (this day of the month).
|
|
409
|
+
if time.localtime().tm_mday in self.days:
|
|
410
|
+
self.action(*self.args, **self.kw)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
class ThreadedScheduler(Scheduler):
|
|
414
|
+
"""A Scheduler that runs in its own thread."""
|
|
415
|
+
|
|
416
|
+
def __init__(self):
|
|
417
|
+
Scheduler.__init__(self)
|
|
418
|
+
# we require a lock around the task queue
|
|
419
|
+
self._lock = threading.Lock()
|
|
420
|
+
|
|
421
|
+
def start(self):
|
|
422
|
+
"""Splice off a thread in which the scheduler will run."""
|
|
423
|
+
self.thread = threading.Thread(target=self._run)
|
|
424
|
+
self.thread.daemon = True
|
|
425
|
+
self.thread.start()
|
|
426
|
+
|
|
427
|
+
def stop(self):
|
|
428
|
+
"""Stop the scheduler and wait for the thread to finish."""
|
|
429
|
+
Scheduler.stop(self)
|
|
430
|
+
with suppress(AttributeError):
|
|
431
|
+
self.thread.join()
|
|
432
|
+
|
|
433
|
+
def _acquire_lock(self):
|
|
434
|
+
"""Lock the thread's task queue."""
|
|
435
|
+
self._lock.acquire()
|
|
436
|
+
|
|
437
|
+
def _release_lock(self):
|
|
438
|
+
"""Release the lock on th ethread's task queue."""
|
|
439
|
+
self._lock.release()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class ThreadedTaskMixin:
|
|
443
|
+
"""A mixin class to make a Task execute in a separate thread."""
|
|
444
|
+
|
|
445
|
+
def __call__(self, schedulerref):
|
|
446
|
+
"""Execute the task action in its own thread."""
|
|
447
|
+
threading.Thread(target=self.threadedcall).start()
|
|
448
|
+
self.reschedule(schedulerref())
|
|
449
|
+
|
|
450
|
+
def threadedcall(self):
|
|
451
|
+
# This method is run within its own thread, so we have to
|
|
452
|
+
# do the execute() call and exception handling here.
|
|
453
|
+
try:
|
|
454
|
+
self.execute()
|
|
455
|
+
except Exception as x:
|
|
456
|
+
self.handle_exception(x)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class ThreadedIntervalTask(ThreadedTaskMixin, IntervalTask):
|
|
460
|
+
"""Interval Task that executes in its own thread."""
|
|
461
|
+
|
|
462
|
+
pass
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class ThreadedSingleTask(ThreadedTaskMixin, SingleTask):
|
|
466
|
+
"""Single Task that executes in its own thread."""
|
|
467
|
+
|
|
468
|
+
pass
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
class ThreadedWeekdayTask(ThreadedTaskMixin, WeekdayTask):
|
|
472
|
+
"""Weekday Task that executes in its own thread."""
|
|
473
|
+
|
|
474
|
+
pass
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
class ThreadedMonthdayTask(ThreadedTaskMixin, MonthdayTask):
|
|
478
|
+
"""Monthday Task that executes in its own thread."""
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
if hasattr(os, "fork"):
|
|
482
|
+
import signal
|
|
483
|
+
|
|
484
|
+
class ForkedScheduler(Scheduler):
|
|
485
|
+
"""A Scheduler that runs in its own forked process."""
|
|
486
|
+
|
|
487
|
+
def __del__(self):
|
|
488
|
+
if hasattr(self, "childpid"):
|
|
489
|
+
os.kill(self.childpid, signal.SIGKILL)
|
|
490
|
+
|
|
491
|
+
def start(self):
|
|
492
|
+
"""Fork off a new process in which the scheduler will run."""
|
|
493
|
+
pid = os.fork()
|
|
494
|
+
if pid == 0:
|
|
495
|
+
# we are the child
|
|
496
|
+
signal.signal(signal.SIGUSR1, self.signalhandler)
|
|
497
|
+
self._run()
|
|
498
|
+
os._exit(0)
|
|
499
|
+
else:
|
|
500
|
+
# we are the parent
|
|
501
|
+
self.childpid = pid
|
|
502
|
+
# can no longer insert in the scheduler queue
|
|
503
|
+
del self.sched
|
|
504
|
+
|
|
505
|
+
def stop(self):
|
|
506
|
+
"""Stop the scheduler and wait for the process to finish."""
|
|
507
|
+
os.kill(self.childpid, signal.SIGUSR1)
|
|
508
|
+
os.waitpid(self.childpid, 0)
|
|
509
|
+
|
|
510
|
+
def signalhandler(self, sig, stack):
|
|
511
|
+
Scheduler.stop(self)
|
|
512
|
+
|
|
513
|
+
class ForkedTaskMixin:
|
|
514
|
+
"""A mixin class to make a Task execute in a separate process."""
|
|
515
|
+
|
|
516
|
+
def __call__(self, schedulerref):
|
|
517
|
+
"""Execute the task action in its own process."""
|
|
518
|
+
pid = os.fork()
|
|
519
|
+
if pid == 0:
|
|
520
|
+
# we are the child
|
|
521
|
+
try:
|
|
522
|
+
self.execute()
|
|
523
|
+
except Exception as x:
|
|
524
|
+
self.handle_exception(x)
|
|
525
|
+
os._exit(0)
|
|
526
|
+
else:
|
|
527
|
+
# we are the parent
|
|
528
|
+
self.reschedule(schedulerref())
|
|
529
|
+
|
|
530
|
+
class ForkedIntervalTask(ForkedTaskMixin, IntervalTask):
|
|
531
|
+
"""Interval Task that executes in its own process."""
|
|
532
|
+
|
|
533
|
+
pass
|
|
534
|
+
|
|
535
|
+
class ForkedSingleTask(ForkedTaskMixin, SingleTask):
|
|
536
|
+
"""Single Task that executes in its own process."""
|
|
537
|
+
|
|
538
|
+
pass
|
|
539
|
+
|
|
540
|
+
class ForkedWeekdayTask(ForkedTaskMixin, WeekdayTask):
|
|
541
|
+
"""Weekday Task that executes in its own process."""
|
|
542
|
+
|
|
543
|
+
pass
|
|
544
|
+
|
|
545
|
+
class ForkedMonthdayTask(ForkedTaskMixin, MonthdayTask):
|
|
546
|
+
"""Monthday Task that executes in its own process."""
|
|
547
|
+
|
|
548
|
+
pass
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
_scheduler_instance = None
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _get_scheduler():
|
|
555
|
+
global _scheduler_instance
|
|
556
|
+
si = _scheduler_instance
|
|
557
|
+
if not si:
|
|
558
|
+
si = ThreadedScheduler()
|
|
559
|
+
_scheduler_instance = si
|
|
560
|
+
return si
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _start_scheduler():
|
|
564
|
+
si = _get_scheduler()
|
|
565
|
+
si.start()
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _stop_scheduler():
|
|
569
|
+
if not _scheduler_instance:
|
|
570
|
+
return
|
|
571
|
+
si = _get_scheduler()
|
|
572
|
+
si.stop()
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def add_interval_task(
|
|
576
|
+
action,
|
|
577
|
+
interval,
|
|
578
|
+
args=None,
|
|
579
|
+
kw=None,
|
|
580
|
+
initialdelay=0,
|
|
581
|
+
processmethod=method.threaded,
|
|
582
|
+
taskname=None,
|
|
583
|
+
):
|
|
584
|
+
si = _get_scheduler()
|
|
585
|
+
return si.add_interval_task(
|
|
586
|
+
action=action,
|
|
587
|
+
interval=interval,
|
|
588
|
+
args=args,
|
|
589
|
+
kw=kw,
|
|
590
|
+
initialdelay=initialdelay,
|
|
591
|
+
processmethod=processmethod,
|
|
592
|
+
taskname=taskname,
|
|
593
|
+
)
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def add_single_task(
|
|
597
|
+
action,
|
|
598
|
+
args=None,
|
|
599
|
+
kw=None,
|
|
600
|
+
initialdelay=0,
|
|
601
|
+
processmethod=method.threaded,
|
|
602
|
+
taskname=None,
|
|
603
|
+
):
|
|
604
|
+
si = _get_scheduler()
|
|
605
|
+
return si.add_single_task(
|
|
606
|
+
action=action,
|
|
607
|
+
args=args,
|
|
608
|
+
kw=kw,
|
|
609
|
+
initialdelay=initialdelay,
|
|
610
|
+
processmethod=processmethod,
|
|
611
|
+
taskname=taskname,
|
|
612
|
+
)
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def add_weekday_task(
|
|
616
|
+
action,
|
|
617
|
+
weekdays,
|
|
618
|
+
timeonday,
|
|
619
|
+
args=None,
|
|
620
|
+
kw=None,
|
|
621
|
+
processmethod=method.threaded,
|
|
622
|
+
taskname=None,
|
|
623
|
+
):
|
|
624
|
+
si = _get_scheduler()
|
|
625
|
+
return si.add_daytime_task(
|
|
626
|
+
action=action,
|
|
627
|
+
taskname=taskname,
|
|
628
|
+
weekdays=weekdays,
|
|
629
|
+
monthdays=None,
|
|
630
|
+
timeonday=timeonday,
|
|
631
|
+
processmethod=processmethod,
|
|
632
|
+
args=args,
|
|
633
|
+
kw=kw,
|
|
634
|
+
)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def add_monthday_task(
|
|
638
|
+
action,
|
|
639
|
+
monthdays,
|
|
640
|
+
timeonday,
|
|
641
|
+
args=None,
|
|
642
|
+
kw=None,
|
|
643
|
+
processmethod=method.threaded,
|
|
644
|
+
taskname=None,
|
|
645
|
+
):
|
|
646
|
+
si = _get_scheduler()
|
|
647
|
+
return si.add_daytime_task(
|
|
648
|
+
action=action,
|
|
649
|
+
taskname=taskname,
|
|
650
|
+
weekdays=None,
|
|
651
|
+
monthdays=monthdays,
|
|
652
|
+
timeonday=timeonday,
|
|
653
|
+
processmethod=processmethod,
|
|
654
|
+
args=args,
|
|
655
|
+
kw=kw,
|
|
656
|
+
)
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def cancel(task):
|
|
660
|
+
si = _get_scheduler()
|
|
661
|
+
si.cancel(task)
|
tgext/scheduler/util.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tgext.scheduler
|
|
3
|
+
Version: 2.0
|
|
4
|
+
Summary: Background task scheduler for TurboGears2
|
|
5
|
+
Author-email: TurboGears Team <turbogears@groups.google.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/TurboGears/tgext.scheduler
|
|
8
|
+
Project-URL: Repository, https://github.com/TurboGears/tgext.scheduler
|
|
9
|
+
Project-URL: Issues, https://github.com/TurboGears/tgext.scheduler/issues
|
|
10
|
+
Keywords: turbogears,tg2,scheduler,background tasks,cron
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Framework :: TurboGears
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/plain
|
|
25
|
+
Requires-Dist: TurboGears2
|
|
26
|
+
|
|
27
|
+
This scheduler is based on TG1's scheduler which was based on Kronos by Irmen de Jong. It makes it easy to have one time or recurring background tasks run as needed
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
tgext/scheduler/__init__.py,sha256=iz0xvEaBu5hBdzATaUvzmHucn9wNz1GVxtq7gUHgIM0,744
|
|
2
|
+
tgext/scheduler/scheduler.py,sha256=NKk_8FW79MVaqptFaEzTbwRXSFuSceshanoIgVRAg3c,20449
|
|
3
|
+
tgext/scheduler/util.py,sha256=7IZc4KkO1gXzAB2l7nhVe-mFezaFoAdZnKpFxwZxO08,207
|
|
4
|
+
tgext_scheduler-2.0.dist-info/METADATA,sha256=3W_E-13CcvoPzrWIEpT4scYYQEOy9KshvppclxEuQbo,1316
|
|
5
|
+
tgext_scheduler-2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
tgext_scheduler-2.0.dist-info/top_level.txt,sha256=9GOdqCqmKLB46HuPrbPBKzHTdFxg1i1NN_HaZm9w_6Q,6
|
|
7
|
+
tgext_scheduler-2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tgext
|