1import datetime
2
3import cron_descriptor
4from celery.schedules import crontab
5from croniter import croniter
6
7
[docs]
8class JobSchedule:
9 """
10 Produce a cron tab spec from text, time periods, or a crontab spec
11
12 Given any specification format, can translate to a human readable
13 text.
14
15 If using time periods (minute, hour, weekday, monthday, month),
16 any argument not specified defaults to '*' for this argument.
17
18 If using text, sepearate each time part (weekday, hour, month)
19 by a comma. To specify multiple times for a part, use / instead
20 of comma.
21
22 Examples::
23
24 # using text
25 JobSchedule('friday, at 06:00/08:00/10:00')
26 JobSchedule('Mondays and Fridays, at 06:00')
27 JobSchedule('every 5 minutes, on weekends, in april')
28
29 # using time periods
30 JobSchedule(weekday='mon-fri', at='06:05,12:05')
31 JobSchedule(weekday='mon-fri', at='06:00')
32 JobSchedule(month='every 2', at='08:00', weekday='every 3')
33
34 # using a crontab spec
35 JobSchedule('05 06,12 * * mon-fri')
36
37 # given a valid specification get human readable text or crontab format
38 JobSchedule('05 06,12 * * mon-fri').text
39 JobSchedule('Mondays and Fridays, at 06:00').cron
40
41 Args:
42 text (str): the natural language specification, with time parts
43 separated by comma
44 at (str): the hh:mm specification, equal to hour=hh, minute=mm
45 minute (str): run on 0-59th minute in every specified hour
46 hour (str): run on 0-23th hour on every specified day
47 weekday (str): run on 0-6th day in every week (0 is Sunday),
48 can also be specified as mon/tue/wed/thu/fri/sat/sun
49 monthday (str): run on 1-31th day in every month
50 month (str): run on 1-12th day of every year
51
52 Raises:
53 ValueError if the given specification is not correct
54
55 .. versionchanged:: 0.18.2
56 the .text property returns times in 24-hour format. Use JobSchedule.cron_descriptor_options to change format.
57 """
58
59 # default cron descriptor options
60 cron_descriptor_options = cron_descriptor.Options(use_24hour_time_format=True)
61
62 def __init__(self, text=None, minute='*', hour='*', weekday='*', monthday='*', month='*', at=None):
63 # if we get text, attempt to convert
64 if text:
65 try:
66 self.sched = self.from_cron(text).sched
67 except Exception:
68 # assume natural language
69 self.sched = self._convert_text(text).sched
70 return
71 # no text, but time periods
72 # get times
73 if at:
74 # 06:00 => hour=6 / minute=00
75 # 06:00,12:00 => hour=6,12 / minute=00
76 hours, minutes = [], []
77 for att in at.split(','):
78 h, m = att.split(':')
79 hours.append(h)
80 minutes.append(m)
81 hour = ','.join(sorted(set(hours)))
82 minute = ','.join(sorted(set(minutes)))
83 # every n => */n
84 minute = self._expand_every(minute)
85 hour = self._expand_every(hour)
86 weekday = self._expand_every(weekday)
87 monthday = self._expand_every(monthday)
88 month = self._expand_every(month)
89 # long to short, e.g. friday => fri
90 weekday = self._convert_weekdays(weekday)
91 # month to number, e.g. january = 1
92 month = self._convert_months(month)
93 # get a cron spec
94 self.sched = crontab(minute=minute, hour=hour, day_of_month=monthday, day_of_week=weekday, month_of_year=month)
95 # make sure the spec can be processed by croniter
96 if not croniter.is_valid(self.cron):
97 raise ValueError("{cronspec} is not a valid schedule")
98
[docs]
99 @classmethod
100 def from_cron(cls, cronspec):
101 """initialize JobSchedule from a cron specifier"""
102 (minute, hour, monthday, month, weekday) = cronspec.split(' ')
103 return JobSchedule(minute=minute, hour=hour, monthday=monthday, month=month, weekday=weekday)
104
[docs]
105 @classmethod
106 def from_text(cls, text):
107 """initialize JobSchedule from a weekday, hour, month specifier"""
108 return JobSchedule(text=text)
109
110 @property
111 def cron(self):
112 """return the cron representation of the schedule"""
113 # adopted from https://docs.celeryproject.org/en/latest/_modules/celery/schedules.html#schedule
114 cron_repr = (
115 '{0._orig_minute} {0._orig_hour} {0._orig_day_of_month} {0._orig_month_of_year} {0._orig_day_of_week}'
116 )
117 return cron_repr.format(self.sched)
118
119 @property
120 def text(self):
121 """return the human readable representation of the schedule
122
123 .. versionchanged:: 0.18.2
124 use JobSchedule.cron_descriptor_options to change format, see https://pypi.org/project/cron-descriptor/
125 """
126 return cron_descriptor.get_description(self.cron, self.cron_descriptor_options)
127
[docs]
128 def next_times(self, n=None, last_run=None):
129 """return the n next times of this schedule, staring from the last run
130
131 Args:
132 n (int): the n next times
133 last_run (datetime): the last time this was run
134
135 Notes:
136 if n is None returns a never ending iterator
137
138 Returns:
139 iterator of next times
140
141 See Also:
142 * croniter.get_next()
143 """
144 iter_next = croniter(self.cron, start_time=last_run)
145 while n > 0 or n is None:
146 yield iter_next.get_next(datetime.datetime)
147 n -= 1 if n > 0 else None
148
149 def __repr__(self):
150 return f'JobSchedule(cron={self.cron}, text={self.text})'
151
152 def _convert_weekdays(self, v):
153 # convert full name weekdays to short
154 days = dict([
155 ('monday', 'mon'),
156 ('tuesday', 'tue'),
157 ('wednesday', 'wed'),
158 ('thursday', 'thu'),
159 ('friday', 'fri'),
160 ('saturday', 'sat'),
161 ('sunday', 'sun'),
162 ('weekday', 'mon-fri'),
163 ('workday', 'mon-fri'),
164 ('working day', 'mon-fri'),
165 ('weekend', 'sat-sun'),
166 ('week-end', 'sat-sun'),
167 ('week end', 'sat-sun'),
168 ])
169 v = v.lower()
170 for full, short in days.items():
171 v = v.replace(full, short)
172 return v
173
174 def _has_month(self, v):
175 months = [
176 'january',
177 'february',
178 'march',
179 'april',
180 'may',
181 'june',
182 'july',
183 'august',
184 'september',
185 'october',
186 'november',
187 'december',
188 ]
189 long = any(m in v for m in months)
190 short = any(m[0:3] in v for m in months)
191 return long or short
192
193 def _has_day(self, v):
194 days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
195 long = any(d in v for d in days)
196 short = any(d[0:3] in v for d in days)
197 return long or short
198
199 def _convert_months(self, v):
200 months = [
201 'january',
202 'february',
203 'march',
204 'april',
205 'may',
206 'june',
207 'july',
208 'august',
209 'september',
210 'october',
211 'november',
212 'december',
213 ]
214 if not self._has_month(v):
215 return v
216 v = v.lower()
217 for m in months:
218 # full
219 start = v.find(m)
220 if start > -1:
221 v = v.replace(m, str(months.index(m) + 1))
222 # short
223 sm = m[0:3]
224 start = v.find(sm)
225 if start > -1:
226 v = v.replace(sm, str(months.index(m) + 1))
227 return v
228
229 def _expand_every(self, v):
230 # convert 'every' specs to cron-like
231 if not isinstance(v, str):
232 return v
233 # every n(nd,rd,th) => */n
234 if '1st' in v or 'first' in v:
235 # 'every 1st' => 1
236 v = '1'
237 if v.startswith('every '):
238 if v.split(' ')[-1].isnumeric():
239 v = v.replace('every ', '*/')
240 else:
241 v = v.replace('every ', '')
242 for order in ('nd', 'rd', 'th'):
243 v = v.replace(order, '')
244 else:
245 # 'every' => *
246 v = v.replace('every', '*')
247 return v.strip()
248
249 def _convert_text(self, text):
250 # experimental natural language text to crontab
251 # every friday
252 specs = {}
253 # ensure single whitespace
254 orig_text = text
255 text = ' '.join(text.split(' ')).lower() + ' '
256 # try placing commas
257 text = text.replace(' at ', ', at ')
258 text = ','.join(part for part in text.split(',') if part)
259
260 # get parts separated by comma
261 parts = [part.strip() for part in text.split(',') if part.strip()]
262 try:
263 specs = self._parse_parts(parts)
264 sched = JobSchedule(**specs)
265 except:
266 raise ValueError(f'Cannot parse {orig_text}, read as {specs}')
267 return sched
268
269 def _parse_parts(self, parts):
270 specs = {}
271 for part in parts:
272 # Monday and Friday => Monday/Friday
273 part = part.replace(' and ', ',')
274 part = part.replace('days', 'day')
275 part = part.replace('hours', 'hour')
276 part = part.replace('minutes', 'minute')
277 part = part.replace('ends', 'end')
278 part = part.replace('on ', '')
279 part = part.replace('only ', '')
280 part = part.replace('in ', '')
281 part = part.replace('/', ',')
282 part = part.replace(' through ', '-')
283 part = part.replace(' until ', '-')
284 part = part.replace(' till ', '-')
285 part = part.replace(' to ', '-')
286 part = part.replace(' of ', '')
287 part = part.replace('from ', '')
288 if 'day' in part and 'month' in part:
289 # day 1 of the month
290 specs['monthday'] = part.replace('day', '').replace('month', '').replace('the', '').strip()
291 elif 'month' in part or 'months' in part:
292 # 'every month', 'every 3rd month', 'every 2 months'
293 specs['month'] = part.replace('months', '').replace('month', '').strip()
294 elif self._has_month(part):
295 # 'january', 'every january'
296 specs['month'] = self._convert_months(part).replace('every', '')
297 elif 'daily' in part:
298 specs['weekday'] = '*'
299 elif self._has_day(part) or 'day' in part or 'week' in part:
300 # 'monday-friday', 'tuesday', 'every 3rd day'
301 part = self._convert_weekdays(part).replace('day', '').strip()
302 # every mon-fri => mon-fri, every fri
303 if 'every ' in part and '-' in part:
304 part = part.replace('every ', '').strip()
305 specs['weekday'] = part
306 elif ':' in part and 'between' not in part:
307 # at 06:00, at 06:00 am
308 specs['at'] = part.replace('at', '').replace('am', '').replace('pm', '').strip()
309 elif ':' in part and 'between' in part:
310 # between 06:00 and 08:00, between 06:00 am and 08:00 am
311 parts = part.replace('between', '').split(',')
312 specs['at'] = parts[0].replace('at', '').replace('am', '').replace('pm', '').strip()
313 elif 'hour' in part and 'past the hour' not in part:
314 # every hour, hour 6, hour 6/7
315 specs['hour'] = part.replace('hour', '').strip()
316 elif 'hour' in part and 'past the hour' in part:
317 # every 5 minutes past the hour
318 time = part.replace('past the hour', '').replace('at', '').replace('minute', '').strip()
319 specs['minute'] = f'*/{time}'
320 elif 'minute' in part:
321 # every minute, every 3rd minute, every 5 minutes, minute 6/7
322 specs['minute'] = part.replace('minute', '').replace('at ', '').strip()
323 return specs