joonis Logo

Crontab Scheduler for Python

Simple Cron-like scheduler for Python with seconds precision.

cron.py [10.42 KB]
  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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*
#
#  Copyright (c) 2011 joonis new media
#  Author: Thimo Kraemer <thimo.kraemer@joonis.de>
#
#  Based on cron.py of Gimli
#  http://www.koders.com/python/fidA55A9DB55093A78DD26B55C606B267B2C5063A79.aspx
#  and crontab.py of the gnome-schedule-1.1.0 package
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02110-1301, USA.

import re
import time
import datetime
import calendar
from threading import Thread, Event

YEAR    = 0
MONTH   = 1
DAY     = 2
HOUR    = 3
MINUTE  = 4
SECOND  = 5
WEEKDAY = 6

class SimpleCrontab(object):
    """Crontab-like scheduler.
    Only deals with the first 5 fields of a normal crontab entry.
    Having 6 fields the first one is used for seconds precision."""

    special = {
            '@reboot'  : '@reboot',
            '@hourly'  : '0 * * * *',
            '@daily'   : '0 0 * * *',
            '@midnight': '0 * * * *',
            '@weekly'  : '0 0 * * 0',
            '@monthly' : '0 0 1 * *',
            '@yearly'  : '0 0 1 1 *',
            '@annually': '0 0 1 1 *',
            }

    field_data = {
            SECOND : {'name': 'Second',  'min': 0, 'max': 59},
            MINUTE : {'name': 'Minute',  'min': 0, 'max': 59},
            HOUR   : {'name': 'Hour',    'min': 0, 'max': 23},
            DAY    : {'name': 'Day',     'min': 1, 'max': 31},
            MONTH  : {'name': 'Month',   'min': 1, 'max': 12,
                        'enum': ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']},
            WEEKDAY: {'name': 'Weekday', 'min': 0, 'max': 7,
                        'enum': ['Sun','Mon','Tue','Wed','Thu','Fri','Sat','Sun']},
            YEAR   : {'name': 'Year'},
            }

    def __init__(self, expr, function, *args, **kwargs):
        self.__thread = None
        self.__stopped = Event()
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.schedule(expr)

    def schedule(self, expr):
        """Sets crontab time fields"""
        if isinstance(expr, str):
            expr = self.special.get(expr, expr)
            expr = expr.split()
        if expr[0] == '@reboot':
            fields = None
        else:
            expr = list(expr)
            if len(expr) == 5:
                expr = ['0'] + expr
            elif len(expr) != 6:
                raise ValueError('Crontab expression needs 5 or 6 fields')
            fields = {
                SECOND  : expr[0],
                MINUTE  : expr[1],
                HOUR    : expr[2],
                DAY     : expr[3],
                MONTH   : expr[4],
                WEEKDAY : expr[5],
                }
            for field, value in fields.items():
                fields[field] = self.__parse_field(field, value)
        self.fields = fields
        if self.is_running():
            self.stop()
            self.start()

    def __parse_field(self, field, value):
        """Parses and verifies crontab time fields"""

        data = self.field_data[field]
        timerange = range(data['min'], data['max']+1)
        errmsg = 'Must be between %s and %s' % (data['min'], data['max'])

        # Replace alias names only if no leading and following alphanumeric and
        # no leading slash is present. Otherwise terms like "JanJan" or
        # "1Feb" would give a valid check. Values after a slash are stepwidths
        # and shouldn't have an alias.
        if data.get('enum'):
            for i, v in enumerate(data['enum']):
                rexp = re.compile('(?<!\w|/)%s(?!\w)' % v, re.IGNORECASE)
                value = rexp.sub(str(i+data['min']), value)

        value = value.replace('*', '%s-%s' % (data['min'], data['max']))

        rexp_step = re.compile('^(\d+-\d+)/(\d+)$')
        rexp_range = re.compile('^(\d+)-(\d+)$')

        expr_range = []
        for value in value.split(','):
            # Get stepwidth
            result = rexp_step.match(value)
            if result:
                value, step = result.groups()
                step = int(step)
                if step == 0 or step not in timerange:
                    raise ValueError('Invalid stepwidth for field "%s": %s' % (data['name'], step))
            else:
                step = 1
            # Get range
            result = rexp_range.match(value)
            if result:
                start, end = result.groups()
                start, end = int(start), int(end)
                if not (start in timerange and end in timerange):
                    raise ValueError('Invalid range for field "%s": %s' % (data['name'], errmsg))
                expr_range.extend(range(start, end+1, step))
            # Should be single number
            elif not value.isdigit():
                raise ValueError('Invalid value for field "%s": %s' % (data['name'], value))
            elif int(value) not in timerange:
                raise ValueError('Value out of range for field "%s": %s' % (data['name'], errmsg))
            else:
                expr_range.append(int(value))

        # Remove duplicates
        expr_range = set(expr_range)
        # Normalize weekdays, 0-Sun -> 7-Sun
        if field == WEEKDAY and 0 in expr_range:
            expr_range.remove(0)
            expr_range.add(7)
        # Sort
        expr_range = list(expr_range)
        expr_range.sort()

        return expr_range

    def __calc_next(self, struct, field, value=None, reset=False):
        """Finds next time of execution given the field arg. If value
        is different than current one resets all other time fields."""

        #print self.field_data[field]['name']
        if value is None:
            value = struct[field] + 1

        if field == DAY:
            # Days need some extra work
            times = []
            last_day = calendar.monthrange(*struct[:2])[1]
            limited_days = len(self.fields[DAY]) != 31
            limited_weekdays = len(self.fields[WEEKDAY]) != 7
            for day in range(1, last_day+1):
                if limited_weekdays:
                    if limited_days and day in self.fields[DAY]:
                        times.append(day)
                    else:
                        weekday = datetime.date(struct[0], struct[1], day).isoweekday()
                        if weekday in self.fields[WEEKDAY]:
                            times.append(day)
                elif day in self.fields[DAY]:
                    times.append(day)
        elif field == YEAR:
            times = [value]
        else:
            times = self.fields[field]

        # Find next time on list
        for v in times:
            if v >= value:
                struct[field] = v
                break
        else:
            # Carry over to previous "parent" field
            self.__calc_next(struct, field-1, reset=True)
            return False

        if field == SECOND:
            return True

        # Reset all following fields if necessary
        if reset or struct[field] != value:
            self.__calc_next(struct, field+1, 0, True)
            return False
        return True

    def next_run(self, starting=None):
        """Calculates when the next execution will be.
        Type of return value depends on type of input value."""
        if not self.fields:
            return
        timestamp = False
        if not starting:
            if starting == 0:
                timestamp = True
            starting = datetime.datetime.now()
        elif not isinstance(starting, datetime.datetime):
            timestamp = True
            starting = datetime.datetime.fromtimestamp(starting)
        struct = [starting.year, -1, -1, -1, -1, -1]
        # Next month is calculated first as next day depends on it.
        # Also if next month is different than time.month the
        # function will set up the rest of the fields
        self.__calc_next(struct, MONTH, starting.month) and \
            self.__calc_next(struct, DAY, starting.day) and \
            self.__calc_next(struct, HOUR, starting.hour) and \
            self.__calc_next(struct, MINUTE, starting.minute) and \
            self.__calc_next(struct, SECOND, starting.second+1)
        next = datetime.datetime(*struct)
        if timestamp:
            next = time.mktime(next.timetuple())
        return next

    def __run(self, wait):
        next = 0
        while True:
            now = max(next, time.time())
            next = self.next_run(now) or now
            self.__stopped.wait(next-now)
            if self.__stopped.isSet():
                break
            thread = Thread(target=self.function, args=self.args, kwargs=self.kwargs)
            thread.start()
            if wait:
                thread.join()
            if next == now:
                break
        self.__stopped.set()

    def is_running(self):
        return self.__thread and self.__thread.isAlive()

    def start(self, wait=False):
        self.__stopped.clear()
        if not self.is_running():
            if not hasattr(self.function, '__call__'):
                raise ValueError('Callback function not callable')
            self.__thread = Thread(target=self.__run, args=(wait,))
            self.__thread.start()

    def stop(self):
        if self.is_running():
            self.__stopped.set()



def main():
    flag = Event()
    flag.set()
    def emit(arg):
        flag.wait()
        flag.clear()
        print datetime.datetime.now(), arg
        flag.set()
    tasks = [
        ('@reboot', 'reboot'),
        ('*   * * * * *', 'every second'),
        ('    * * * * *', 'every minute'),
        ('  */2 * * * *', 'every two minutes'),
        ('* */3 * * * *', 'every second every three minutes'),
        ]
    crontabs = []
    for expr, text in tasks:
        cron = SimpleCrontab(expr, emit, text)
        cron.start()
        crontabs.append(cron)
    try:
        raw_input('\nPress "Enter" to quit\n\n')
    finally:
        for cron in crontabs:
            cron.stop()


if __name__ == "__main__":
    main()

Can I
  help you?


Just drop me a line at
giraffe@joonis.de