Cron Expression Parser in PHP

Working with cron scheduling can many times be a frustrating affair. Although setting a few cron jobs at one time can be easy, calculating cron dates in the future in code can get time consuming quickly. The PHP cron expression parser described here can parse a CRON expression, determine if it is due to run, calculate the next run date of the expression or calculate the previous run date of the expression. You can calculate dates far into the future or past by skipping n number of matching dates.

The library is available as a composer package so install the library using the same. You can also download the same from github.

c:\localhost>composer require mtdowling/cron-expression

A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows:

*    *    *    *    *    *
-    -    -    -    -    -
|    |    |    |    |    |
|    |    |    |    |    + year [optional]
|    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
|    |    |    +---------- month (1 - 12)
|    |    +--------------- day of month (1 - 31)
|    +-------------------- hour (0 - 23)
+------------------------- min (0 - 59)

Usage

Load the library using autoload and create a cron factory object using a cron expression or some predefined values.

require_once './vendor/autoload.php';
 
// Works with predefined scheduling definitions
$cron = Cron\CronExpression::factory('@daily');
//OR
$cron = Cron\CronExpression::factory('0 0 * * *');

Various predefined scheduling definitions are available:

`@yearly    - Run once a year, midnight, Jan. 1 - 0 0 1 1 *
`@annually` - Run once a year, midnight, Jan. 1 - 0 0 1 1 *
`@monthly`  - Run once a month, midnight, first of month - 0 0 1 * *
`@weekly`   - Run once a week, midnight on Sun - 0 0 * * 0
`@daily`    - Run once a day, midnight - 0 0 * * *
`@hourly`   - Run once an hour, first minute - 0 * * * *

Once we have got the cron object in the variable we can now determine cron times in the future, past or if it is currently to be scheduled.

<?php
 
require_once './vendor/autoload.php';
 
// Works with predefined scheduling definitions
$cron = Cron\CronExpression::factory('@daily');
//Here @daily we assume a date of July 20 2015,
// the date when this post was written.
 
if($cron->isDue()) {
    echo 'cron is now due.';
    // do something here...
}
 
// Get next cron run datetime
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
// 2015-07-22 00:00:00
 
 
// Get previous cron run datetime
echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');
// 2015-07-21 00:00:00
 
 
// Factory method even works with complex expressions
$cron = Cron\CronExpression::factory('3-59/15 2,6-12 */15 1 2-5');
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
// 2016-01-15 02:03:00
 
 
// Calculate a run date two iterations into the future
$cron = Cron\CronExpression::factory('@daily');
echo $cron->getNextRunDate(null, 2)->format('Y-m-d H:i:s');
// 2015-07-24 00:00:00
 
// Calculate a run date relative to a specific time
$cron = Cron\CronExpression::factory('@monthly');
echo $cron->getNextRunDate('2015-08-12 00:00:00')->format('Y-m-d H:i:s');
// 2015-09-01 00:00:00

The various methods return the date in the PHP DateTime format which allows us to chain the DateTime ‘format’ method to easily process dates.

If you want to know the last 5 run dates, you can use the getMultipleRunDates() method and set the $invert argument to true:

$cron = Cron\CronExpression::factory('@daily');
 
foreach ($cron->getMultipleRunDates(5, 'now', true) as $date) {
    echo $date->format('Y-m-d H:i:s') . PHP_EOL;
}
/*
Note we get the following dates because we have set the cron factory
value to @daily.
 
2015-07-21 00:00:00
2015-07-20 00:00:00
2015-07-19 00:00:00
2015-07-18 00:00:00
2015-07-17 00:00:00
*/

You can see if a cron expression matches a specific date by calling the isDue() method with a specific date.

$cron = Cron\CronExpression::factory('@monthly');
 
if ($cron->isDue('August 1, 2016')) {
    echo "Cron is due";
}


One thought on “Cron Expression Parser in PHP

Comments are closed.