Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

algorithm - Calculate when a cron job will be executed then next time

I have a cron "time definition"

1 * * * * (every hour at xx:01)
2 5 * * * (every day at 05:02)
0 4 3 * * (every third day of the month at 04:00)
* 2 * * 5 (every minute between 02:00 and 02:59 on fridays)

And I have an unix timestamp.

Is there an obvious way to find (calculate) the next time (after that given timestamp) the job is due to be executed?

I'm using PHP, but the problem should be fairly language-agnostic.

[Update]

The class "PHP Cron Parser" (suggested by Ray) calculates the LAST time the CRON job was supposed to be executed, not the next time.

To make it easier: In my case the cron time parameters are only absolute, single numbers or "*". There are no time-ranges and no "*/5" intervals.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a PHP project that is based on dlamblin's psuedo code.

It can calculate the next run date of a CRON expression, the previous run date of a CRON expression, and determine if a CRON expression matches a given time. You can skip This CRON expression parser fully implements CRON:

  1. Increments of ranges (e.g. */12, 3-59/15)
  2. Intervals (e.g. 1-4, MON-FRI, JAN-MAR )
  3. Lists (e.g. 1,2,3 | JAN,MAR,DEC)
  4. Last day of a month (e.g. L)
  5. Last given weekday of a month (e.g. 5L)
  6. Nth given weekday of a month (e.g. 3#2, 1#1, MON#4)
  7. Closest weekday to a given day of the month (e.g. 15W, 1W, 30W)

https://github.com/mtdowling/cron-expression

Usage (PHP 5.3+):

<?php

// Works with predefined scheduling definitions
$cron = CronCronExpression::factory('@daily');
$cron->isDue();
$cron->getNextRunDate();
$cron->getPreviousRunDate();

// Works with complex expressions
$cron = CronCronExpression::factory('15 2,6-12 */15 1 2-5');
$cron->getNextRunDate();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...