Calculate next scheduled time based on cron spec

我怕爱的太早我们不能终老 提交于 2019-12-02 20:39:33

Just looking at it, I think you need to:

  • parse the chron spec to five arrays containing acceptable values for each field;
  • parse 'now' to a value for each field;
  • in order of minute, hour, {day-of-month OR day-of-week}, month-of year: find the lowest array value that matches or exceeds the current value, correcting for carry.

I don't know how to handle day-of-week and day-of-month simultaneously; I am sure there is a way, but on the other hand I don't think I've ever seen a spec that actually specified both. I think it would be sufficient to write a handler for either and throw an error if you receive both.

Edit: apparently if day-of-week and day-of-month are both specified, it is supposed to fire on both - ie if the rule is '15th, Wednesday' it will fire on every 15th and every Wednesday.

The croniter package does what you want:

import croniter
import datetime

now = datetime.datetime.now()
sched = '1 15 1,15 * *'    # at 3:01pm on the 1st and 15th of every month
cron = croniter.croniter(sched, now)

for i in range(4):
    nextdate = cron.get_next(datetime.datetime)
    print nextdate

prints

2011-01-15 15:01:00
2011-02-01 15:01:00
2011-02-15 15:01:00
2011-03-01 15:01:00

although it would be nice if it were written as an actual iterator. Maybe I've got my next project ;-)

Later.js is a javascript library that does just this. It is able to parse a Cron expression and then calculate future occurrences of the schedule. It's algorithm isn't very fancy, but it does the job. Might be worth a look.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!