计算基础上的cron规范下次预定时间基础上、下次、时间、cron

2023-09-11 00:00:28 作者:日不西沉

什么是计算给定当前时间和一个cron规范?事件的下次运行时间的有效方式。

What's an efficient way to calculate the next run time of an event given the current time and a cron spec?

我在找的东西比其他,通过每分钟检查循环,如果它符合规范。

I'm looking for something other than "loop through every minute checking if it matches spec".

规范的例子可能是:

在每个月1日和15日15:01 在10,20,30,40,50分钟过去一小时每隔一小时

Python的code是可爱的,但伪code或高层次的描述也将是AP preciated。

Python code would be lovely but psuedo code or high level description would also be appreciated.

[更新]假设该规范已经被解析,并在一些合理的格式。

[Update] Assume the spec is already parsed and is in some reasonable format.

推荐答案

只是看着它,我想你需要:

Just looking at it, I think you need to:

解析代上规范包含可接受值的每个外地5阵列; 在解析现在为每个字段的值; 在命令分钟,小时,{日,周或日-个月}个月的一年:找到最低数组值符合或超过当前值,校正携带

我不知道如何处理日常-的同时每周日-的一个月;我相信,有一种方法,但在另一方面,我不认为我见过,实际上指定了一个规范。我认为这将是足以写一个处理程序,或者如果您收到这两个抛出一个错误。的

编辑:显然天的星期天个月,如果都被指定,它应该是开枪的两个 - 也就是说,如果规则是 15日,周三将火上每隔14个和每星期三。

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.

该croniter包你想要做什么:

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

打印

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 ;-)

 
精彩推荐
图片推荐