Added support for initial offset

This commit is contained in:
Maximilian Giller 2022-04-27 22:38:00 +02:00
parent d3e58dbe3b
commit e29bf2baf6
3 changed files with 26 additions and 12 deletions

View file

@ -5,10 +5,11 @@ Each job runs on a separate thread and when the service is shut down, it waits t
Inspired by this blog [`here`](https://www.g-loaded.eu/2016/11/24/how-to-terminate-running-python-threads-using-signals/) Inspired by this blog [`here`](https://www.g-loaded.eu/2016/11/24/how-to-terminate-running-python-threads-using-signals/)
## Fork
This fork aims to provide some improvements to the original library. Mainly to be able to set a start time or start offset for tasks.
## Installation ## Installation
```sh Has to be installed manually atm. Since it is just a fork of the original and I still have to set that up and want to respect the work of Sankalp Jonna. Feel free to help tho!
pip install timeloop
```
## Writing jobs ## Writing jobs
```python ```python
@ -28,9 +29,10 @@ def sample_job_every_5s():
print "5s job current time : {}".format(time.ctime()) print "5s job current time : {}".format(time.ctime())
@tl.job(interval=timedelta(seconds=10)) # Added support of initial offset!
def sample_job_every_10s(): @tl.job(interval=timedelta(seconds=10), offset=timedelta(hours=1))
print "10s job current time : {}".format(time.ctime()) def sample_job_after_an_hour_every_10s():
print "after an hour 10s job current time : {}".format(time.ctime())
``` ```
## Start time loop in separate thread ## Start time loop in separate thread

View file

@ -1,3 +1,4 @@
from datetime import datetime, timedelta
import logging import logging
import sys import sys
import signal import signal
@ -20,8 +21,8 @@ class Timeloop():
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
self.logger = logger self.logger = logger
def _add_job(self, func, interval, *args, **kwargs): def _add_job(self, func, interval: timedelta, offset: timedelta=None, *args, **kwargs):
j = Job(interval, func, *args, **kwargs) j = Job(interval, func, offset=offset *args, **kwargs)
self.jobs.append(j) self.jobs.append(j)
def _block_main_thread(self): def _block_main_thread(self):
@ -46,9 +47,15 @@ class Timeloop():
self.logger.info("Stopping job {}".format(j.execute)) self.logger.info("Stopping job {}".format(j.execute))
j.stop() j.stop()
def job(self, interval): def job(self, interval: timedelta, offset: timedelta=None):
"""Decorator to define a timeloop for the decorated function.
Args:
interval (timedelta): How long to wait after every execution until the next one.
offset (timedelta, optional): Positive offset until the first execution of the function. If None, will wait with first execution until the first interval passed. If timedelta with length 0 (or smaller) will execute immediately. Defaults to None.
"""
def decorator(f): def decorator(f):
self._add_job(f, interval) self._add_job(f, interval, offset=offset)
return f return f
return decorator return decorator

View file

@ -1,12 +1,14 @@
from threading import Thread, Event from threading import Thread, Event
from datetime import timedelta from datetime import timedelta
from time import sleep
class Job(Thread): class Job(Thread):
def __init__(self, interval, execute, *args, **kwargs): def __init__(self, interval: timedelta, execute, offset: timedelta=None, *args, **kwargs):
Thread.__init__(self) Thread.__init__(self)
self.stopped = Event() self.stopped = Event()
self.interval = interval self.interval: timedelta = interval
self.execute = execute self.execute = execute
self.offset: timedelta = offset
self.args = args self.args = args
self.kwargs = kwargs self.kwargs = kwargs
@ -15,5 +17,8 @@ class Job(Thread):
self.join() self.join()
def run(self): def run(self):
if self.offset:
sleep(self.offset.total_seconds())
while not self.stopped.wait(self.interval.total_seconds()): while not self.stopped.wait(self.interval.total_seconds()):
self.execute(*self.args, **self.kwargs) self.execute(*self.args, **self.kwargs)