Created
August 26, 2014 16:38
-
-
Save markrwilliams/fcff6f36c8a50556587d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from collections import namedtuple | |
ANY = '*' | |
class JobTime(namedtuple('JobTime', ['minute', 'hour', | |
'day_of_month', | |
'month', 'day_of_week'])): | |
_field_to_datetime = [('month', 'month'), | |
('day_of_month', 'day'), | |
('hour', 'hour'), | |
('minute', 'minute')] | |
# 'day_of_week': 'weekday'} | |
@classmethod | |
def fromlist(cls, spec): | |
return cls(*[slot if slot == ANY else int(slot) for slot in spec]) | |
def to_datetime(self): | |
now = datetime.now() | |
args = [now.year] | |
items = self._asdict() | |
for field, name in self._field_to_datetime: | |
item = items[field] | |
if item == ANY: | |
item = getattr(now, name) | |
args.append(item) | |
dt = datetime(*args) | |
if self.day_of_week != ANY and self.day_of_month != ANY: | |
if self.day_of_week != dt.weekday: | |
raise ValueError("%r won't run this year!" % self) | |
elif self.day_of_week != ANY and self.day_of_month == ANY: | |
difference = self.day_of_week - dt.weekday() | |
offset = (7 + difference) % 7 | |
return dt.replace(day=dt.day + offset) | |
else: | |
return dt | |
def parse(spec): | |
parts = spec.split(None, 5) | |
if len(parts) != 6: | |
raise ValueError | |
time_spec, command = parts[:5], parts[5:] | |
return JobTime.fromlist(time_spec) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment