Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
BlaM Avatar asked Nov 26 '08 17:11

BlaM


1 Answers

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 = Cron\CronExpression::factory('@daily'); $cron->isDue(); $cron->getNextRunDate(); $cron->getPreviousRunDate();  // Works with complex expressions $cron = Cron\CronExpression::factory('15 2,6-12 */15 1 2-5'); $cron->getNextRunDate(); 
like image 188
Michael Dowling Avatar answered Sep 19 '22 19:09

Michael Dowling