Parse/evaluate/generate CrontabExpressions outside of linux?

匆匆过客 提交于 2019-12-01 10:58:29

问题


I'm building some software that needs a scheduling input, and I'd really like to re-use the design of crontab because it simply works.

CrontabExpressions can be really simple */5 * * * * "run every five minutes" or more complex 2-59/3 1,9,22 11-26 1-6 ? 2003 "In 2003 on the 11th to 26th of each month in January to June every third minute starting from 2 past 1am, 9am and 10pm".

I am not looking to use the linux software called crontab, I'm seeking a way I can evaluate these expressions correctly (for instance, output the next 25 timestamps that match the crontab, or generate it based on some abstracted GUI for the users).

I can't really find any libraries or functions that do this in JavaScript or PHP or even other languages. If they don't exist, what would be a good method to do this? I already know an overly-complicated regular expression is likely to be the wrong answer. I'm having a hard time finding the C source code in crontab that does this task as well, which makes me believe it might not take place here?


回答1:


To output the next 25 timestamps that match the crontab you could use crontab Python module:

from datetime import datetime, timedelta
import crontab

tab = crontab.CronTab('2-59/3 1,9,22 11-26 1-6 ? 2012')

dt = datetime.now()
for _ in xrange(25):
    delay = tab.next(dt) # seconds before this crontab entry can be executed.
    dt += timedelta(seconds=delay)
    print(dt)

Output

2012-01-11 22:41:00
2012-01-11 22:44:00
2012-01-11 22:47:00
2012-01-11 22:50:00
2012-01-11 22:53:00
2012-01-11 22:56:00
2012-01-11 22:59:00
2012-01-12 01:02:00
2012-01-12 01:05:00
2012-01-12 01:08:00
2012-01-12 01:11:00
2012-01-12 01:14:00
2012-01-12 01:17:00
2012-01-12 01:20:00
2012-01-12 01:23:00
2012-01-12 01:26:00
2012-01-12 01:29:00
2012-01-12 01:32:00
2012-01-12 01:35:00
2012-01-12 01:38:00
2012-01-12 01:41:00
2012-01-12 01:44:00
2012-01-12 01:47:00
2012-01-12 01:50:00
2012-01-12 01:53:00

There is also python-crontab that provides crontab module but with richer functionality (parse/generate).




回答2:


There is a Java library as part of the Quartz Scheduler which can be used to evaluate cron expressions quite easily.

The class CronExpression yields methods like isSatisfiedBy(Date date) or getNextValidTimeAfter(Date date) which is very useful.

The library is freely available.



来源:https://stackoverflow.com/questions/8714737/parse-evaluate-generate-crontabexpressions-outside-of-linux

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