PHP Classes

PHP Cron Scheduler Parser: Compute the time of scheduled jobs in cron format

Recommend this page to a friend!
  Info   View files Example   View files View files (3)   DownloadInstall with Composer Download .zip   Reputation   Support forum (2)   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 692 All time: 4,723 This week: 206Up
Version License PHP version Categories
csd-parser 2GNU Lesser Genera...5PHP 5, Time and Date
Description 

Author

This class can compute the time of scheduled jobs in cron format.

It takes the definition of task schedule in the format used by the cron program and computes the time of future or past job schedule times.

The class may compute the schedule times relatively to the current time or some other given time moment.

Picture of Chris Volwerk
  Performance   Level  
Name: Chris Volwerk <contact>
Classes: 1 package by
Country: The Netherlands The Netherlands
Age: 41
All time rank: 284775 in The Netherlands The Netherlands
Week rank: 280 Up7 in The Netherlands The Netherlands Up

Example

<?php

$format
= 'D d-m-y H:i'; // Will output dates like this in example
$basetime = date('d-m-Y H:00'); // A (default) base time for consistancy in example
$schedule = '1 3 2-8/6 * 2,3'; // A (default) scheduling definition
$schedule2 = '0 0 15 * *'; // A (2nd default) scheduling definition
$output = '';

if(isset(
$_GET['schedule'])) {

    function
echo_errors($errno, $message) {
        echo
'<h1>Error:</h1><pre>'.$message.'</pre>';
    }

   
error_reporting(E_ALL);
   
set_error_handler('echo_errors');

   
ob_start();
    require(
'csd_parser.php');
   
$basetime = $_GET['basetime'];
   
$schedule = $_GET['schedule'];
   
$schedule2 = $_GET['schedule2'];

   
// Create a new parser, basetime is optional by thw way, it will default to the current time
   
try {
       
$parser = new csd_parser($schedule, $basetime);
        echo
'<div style="margin: 5px 0 0; color: gray;">$parser = new csd_parser($schedule, $basetime)</div>';

       
// Output next time cron should run, 3 different ways ("next" is default)
       
echo '<h3>Next runtime, 3 different ways</h3>';
        echo
date($format, $parser->get()).' <span style="margin-left: 20px; color: gray">$parser->get()</span><br />';
        echo
date($format, $parser->get('next')).' <span style="margin-left: 20px; color: gray">$parser->get(\'next\')</span><br />';
        echo
date($format, $parser->get(0)).' <span style="margin-left: 20px; color: gray">$parser->get(0)</span><br />';

       
// And the last time it was supposed to run, 3 different ways
       
echo '<h3>Last runtime, 3 different ways</h3>';
        echo
date($format, $parser->get('last')).' <span style="margin-left: 20px; color: gray">$parser->get(\'last\')</span><br />';
        echo
date($format, $parser->get('prev')).' <span style="margin-left: 20px; color: gray">$parser->get(\'prev\')</span><br />';
        echo
date($format, $parser->get(-1)).' <span style="margin-left: 20px; color: gray">$parser->get(-1)</span><br />';

       
// The next 3 times it's supposed to run
       
echo '<h3>The next 3 runtimes</h3>';
        for(
$i = 0; $i < 3; $i++) {
            echo
date($format, $parser->get($i)).' <span style="margin-left: 20px; color: gray">$parser->get('.$i.')</span><br />';
        }

       
// Try a different schedule
       
echo '<h3>The next 3 runtimes, with 2<sup>nd</sup> schedule</h3>';
       
$parser = new csd_parser($schedule2, $basetime);
        for(
$i = 0; $i < 3; $i++) {
            echo
date($format, $parser->get($i)).' <span style="margin-left: 20px; color: gray">$parser->get('.$i.')</span><br />';
        }

        try {

           
// And now with both combined
            // Note that you can also use text, separating schedules with newlines (allows for input trough e.g. a textarea)
           
echo '<h3 style="margin-bottom: 0px">Combine the above two schedules and calc next 3 runtimes</h3>';
            echo
'<div style="margin: 5px 0 12px; color: gray;">$parser = new csd_parser(array($schedule, $schedule2), $basetime)</div>';
           
$parser = new csd_parser(array($schedule, $schedule2), $basetime);
            for(
$i = 0; $i < 3; $i++) {
                echo
date($format, $parser->get($i)).' <span style="margin-left: 20px; color: gray">$parser->get('.$i.')</span><br />';
            }

           
// All runtimes of the next past months
            // Note the use of (string) to indicate this is NOT an offset
           
echo '<h3 style="margin-bottom: 0px">All the runtimes of the past 3 months</h3>';
            echo
'<div style="margin: 5px 0 12px; color: gray;">$parser->get( (string) strtotime(\'-3 month\', strtotime($basetime)) )</div>';
           
$untill = strtotime('-3 month', strtotime($basetime));
           
$times = $parser->get((string)$untill);
            foreach(
$times as $time) {
                echo
date($format, $time).'<br />';
            }

           
// Quickly fetch with static function csd_parser::calc
            // Note that each call to the static function parses AND calculates everything anew
            // it will thus be slower if you want to calculate subsequent times
           
echo '<h3 style="margin-bottom: 0px">Calc next runtime using the static function</h3>';
            echo
'<div style="margin: 5px 0 12px; color: gray;">csd_parser::calc($schedule, 0, $basetime)</div>';
           
$time = csd_parser::calc($schedule, 0, $basetime);
            echo
date($format, $time);
        } catch(
Exception $e) {
            echo
'<h1>Exception:</h1><pre>'.$e->getMessage().'</pre>';
        }
    } catch(
Exception $e) {
        echo
'<h1>Exception:</h1><pre>'.$e->getMessage().'</pre>';
    }

   
$output = '<hr>'.ob_get_clean();
}

echo <<<EOF
<html>
<body style="font-family: monospace;">
<h3>Generate examples with</h3>
<form>
  <span style="display: inline-block; width: 100px">Schedule:</span><input type="text" value="
$schedule" name="schedule" style="width: 200px; font-family: monospace" /> [<a href="http://en.wikipedia.org/wiki/Cron#CRON_expression" target=_blank">Help</a>]<br />
  <span style="display: inline-block; width: 100px">2<sup>nd</sup> Schedule:</span><input type="text" value="
$schedule2" name="schedule2" style="width: 200px; font-family: monospace" ><br />
  <span style="display: inline-block; width: 100px">Time:</span><input type="text" value="
$basetime" name="basetime" style="width: 200px; font-family: monospace" >
  <input type="submit" value="Generate" />
  <a href="examples.php"><button type="button">Reset</button></a>
</form>
$output
</body>
</html>
EOF;


Details

Class for easy calculation of UNIX timestamps from cron scheduling definitions Created: May 27th 2013 Author: Volwerk, C Contact: vollie [at] vollie [dot] net License: LGPLv3 About ================================================================================ This class can calculate a (range of) unix timestamp(s) of either future or past occurences relative to a given time considering a single or a combination of multiple scheduling definitions. I made this class after finding most classes capable of parsing cron scheduling definitions either bloated or lacking in functionality. This was written to be completely independent of other classes, non-standard functionalities and frame- works, be bug-free, calculate reasonably fast and have little overhead. Features ================================================================================ - Full support of 'traditional' crontab format including ranges, increments and multiple list items, allowing for advanced statements, e.g.: 5-10 12 1-10/2,*/5 * 2,3 2013 - Support for combining multiple statements using an or like approach. e.g.: "0 10 * * *" combined with "0 0 5 * *" would run every day at 10 and once a month at 0:00 on the 5th. - Get both future and paste times by offset (e.g. 5 crons from now). - Get a range of times (e.g. from now untill one month from now). - Support for named entries (e.g. "monday" or "mon" instead of 1, or "june" or "jun" instead of 6). - Identifies error in definitions and trows 'regular' (supressable) errors for them identifying the list item and line in the error. - Overlaps, duplicates or out of range entries are corrected. - Calculate relative to an optionally provided (custom) time Usage ================================================================================ You can use either a static approach or create a new parser. E.g the below two options both fetch $which runtime(s) of $cron_string relative to $start_point. csd_parser::calc($cron_string, $which, $start_point); $parser = new csd_parser($cron_string, $start_point); $parser->get($which); For more (advanced) examples (and explanation of what they'll do) glance over the example.php file. It can be easily adjusted to run some tests as well. It is worth noting that the static approach always reparses and recalculates. So if you want multiple times, creating a new object will be (slightly) faster. Who can use this class? ================================================================================ Anyone who wants to use cron-like scheduling for anything other than 'pure' cron jobs, or who wants to avoid the relative hassle of creating (seperate) crons for every scheduled task. e.g.: Our own system simply runs one cron every minute which in turn picks and reschedules jobs that can easily be scheduled, configured and even written using forms in the administrative area. changes ================================================================================ Sep 1st 2014 - Fixed issue that may occur when calculating into the future stemming from compensation for leap years - Slightly increased performance Jul 31st 2017 - Fixed issue relating to weekday numbers which led to skipping an entire week instead of resuming on the earliest next weekday

  Files folder image Files  
File Role Description
Plain text file csd_parser.php Class The CSD Parser Class
Accessible without login Plain text file examples.php Example Usage Examples
Accessible without login Plain text file readme.txt Doc. Readme File

 Version Control Unique User Downloads Download Rankings  
 0%
Total:692
This week:0
All time:4,723
This week:206Up
User Comments (1)