File size: 1,423 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 | import threading
import math
class IntervalSchedule:
def __init__(self, seconds):
self.seconds = float(seconds)
if not math.isfinite(self.seconds) or self.seconds <= 0:
raise ValueError("interval seconds must be a positive finite number")
class CronScheduler:
def __init__(self):
self.jobs = []
self._stop = threading.Event()
self._threads = []
self._running = False
def add_interval_job(self, seconds, func):
if not callable(func):
raise TypeError("interval callback must be callable")
if self._running:
raise RuntimeError("register jobs before starting the scheduler")
self.jobs.append((IntervalSchedule(seconds), func))
def _run_job(self, schedule, func):
while not self._stop.wait(schedule.seconds):
func()
def start(self):
if self._running:
return
self._stop = threading.Event()
self._threads = []
for schedule, func in self.jobs:
thread = threading.Thread(target=self._run_job, args=(schedule, func), daemon=True)
thread.start()
self._threads.append(thread)
self._running = True
def stop(self):
if not self._running:
return
self._stop.set()
for thread in self._threads:
thread.join(timeout=1)
self._running = False
|