aboutsummaryrefslogtreecommitdiff
path: root/src/core_modules/cron.py
blob: 69e0105b623aecdefed1fee87016de001d5ed87a (about) (plain) (blame)
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
import datetime, time
from src import ModuleManager, utils

class Module(ModuleManager.BaseModule):
    def on_load(self):
        now = datetime.datetime.utcnow()
        next_minute = now.replace(second=0, microsecond=0)
        next_minute += datetime.timedelta(minutes=1)
        until = time.time()+((next_minute-now).total_seconds())
        self.timers.add("cron", self._minute, 60, until)

    def _minute(self, timer):
        now = datetime.datetime.utcnow().replace(second=0, microsecond=0)
        timer.redo()

        timestamp = [now.minute, now.hour]

        events = self.events.on("cron")
        event = events.make_event()
        for cron in events.get_hooks():
            schedule = cron.get_kwarg("schedule").split(" ")

            if self._schedule_match(timestamp, schedule):
                cron.call(event)

    def _schedule_match(self, timestamp, schedule):
        for timestamp_part, schedule_part in zip(timestamp, schedule):
            if not self._schedule_match_part(timestamp_part, schedule_part):
                return False
        return True

    def _schedule_match_part(self, timestamp_part, schedule_part):
        if "," in schedule_part:
            for schedule_part in schedule_part.split(","):
                if self._schedule_match_part([timestamp_part], [schedule_part]):
                    return True

        elif schedule_part.startswith("*/"):
            schedule_step = int(schedule_part.split("*/", 1)[1])
            if (timestamp_part%schedule_step) == 0:
                return True

        elif "-" in schedule_part:
            left, right = schedule_part.split("-", 1)
            return int(left) <= timestamp_part <= int(right)

        elif schedule_part == "*":
            return True

        elif timestamp_part == int(schedule_part):
            return True

        return False