expephalon/core/classes/cron.py
Klaus-Uwe Mitterer 27fe413d11 Some refactoring to get cron running
Moved dbsettings documentation to Gitlab wiki
2020-05-24 17:44:27 +02:00

38 lines
No EOL
1.2 KiB
Python

from django.utils import timezone
from core.models.cron import CronLog
from dbsettings.functions import getValue
from parse_crontab import CronTab
class Cronjob:
def __init__(self, name, crondef, lock=getValue("core.cron.lock", 300)):
self.name = name
self.crondef = crondef
self.lock = lock
@property
def is_running(self):
now = timezone.now()
maxage = now - timezone.timedelta(seconds=self.lock)
CronLog.objects.filter(task=self.name, locked=True, execution__lt=maxage).update(locked=False)
return True if CronLog.objects.filter(task=self.name, locked=True) else False
@property
def next_run(self):
runs = CronLog.objects.filter(task=self.name)
if not runs:
CronLog.objects.create(task=self.name, locked=False)
return self.next_run
lastrun = runs.latest("execution").execution
return lastrun + timezone.timedelta(seconds=CronTab(self.crondef).next(lastrun))
@property
def is_due(self):
return self.next_run <= timezone.now()
def run(self):
from core.tasks.cron import run_cron
run_cron.delay(self.name)