summaryrefslogtreecommitdiff
path: root/postgresqleu/scheduler/util.py
blob: 5a3177e98ca4adb05b597e8d2de7e9ea4f1bb647 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from django.db import connection
from django.utils import timezone

from datetime import timedelta


def notify_job_change():
    with connection.cursor() as curs:
        curs.execute("NOTIFY pgeu_scheduled_job")


def trigger_immediate_job_run(command, delay=None):
    from .models import ScheduledJob

    j = ScheduledJob.objects.get(command=command)
    if delay:
        j.nextrun = timezone.now() + delay
    else:
        j.nextrun = timezone.now()
    j.save(update_fields=['nextrun'])
    notify_job_change()


def _get_next_time(times):
    # Next time will be the first one that's after current time
    current = timezone.now().time()
    stimes = sorted(times)
    for t in stimes:
        if t > current:
            return timezone.now().replace(hour=t.hour, minute=t.minute, second=t.second, microsecond=0)
            break
    else:
        return timezone.now().replace(hour=stimes[0].hour,
                                      minute=stimes[0].minute,
                                      second=stimes[0].second,
                                      microsecond=0) + timedelta(hours=24)


# Calculate the next time for this job
def reschedule_job(job, save=True, notify=False):
    if (notify and not save):
        raise Exception("It makes no sense to notify if not saving!")

    if not job.enabled:
        if job.nextrun:
            job.nextrun = None
            if save:
                job.save()
        return

    newtime = None
    # First check for overrides
    if job.override_interval:
        newtime = job.last_run_or_skip(timezone.now()) + job.override_interval
    elif job.override_times:
        newtime = _get_next_time(job.override_times)
    elif job.scheduled_interval:
        newtime = job.last_run_or_skip(timezone.now()) + job.scheduled_interval
    elif job.scheduled_times:
        newtime = _get_next_time(job.scheduled_times)

    job.nextrun = newtime
    if save:
        job.save()
        if notify:
            notify_job_change()