PHP Classes

File: twzCron-doc.txt

Recommend this page to a friend!
  Classes of Tony  >  twzCronChart  >  twzCron-doc.txt  >  Download  
File: twzCron-doc.txt
Role: Documentation
Content type: text/plain
Description: Class reference
Class: twzCronChart
Parse crontab schedule and generate Gantt charts
Author: By
Last change: updated for changes to class
Date: 0 years ago
Size: 10,347 bytes


Class file image Download
twzCronChart    v1.1.4 2015-10-28

In this document:
    1. Introduction
    2. Instantiation
    3. Public methods
    4. CSS class names
    5. Limitations


1. Introduction

twzCronChart is a PHP5 class that shows a simple Gantt chart of cron tasks,
by parsing the crontab to extract task and scheduling information. The class 
also provides methods to retrieve the number of cron tasks, the cron line 
for each task, and the next or last date for any task.

Nothing is echoed by the class. This makes it easier for you to manipulate 
any output to your liking before sending it to the browser (or where ever).


2. Instantiation

After including the class, simply create a new instance like this:

    $cron = new twzCronChart();

This will read and parse your crontab (obtained by executing "crontab -l").
Alternatively, you can read a crontab from elsewhere and pass it to the class
as a string or array using PHP's file_get_contents() or file() function:

    $MyCron = file('../path/mycron.cron');
    $cron = new twzCronChart($MyCron);


3. Public methods

->Chart - generate a cron chart
    This is main purpose of the twzCronChart class; it returns the html for a 
    gantt chart, or boolean false on error. Before calling this method, you can 
    set various options with other methods, eg SetChartName(), SetTaskNames().
    You can style the chart to suit your preferences using CSS.
        FromDate ...... string or int representing the first date for the chart 
                        (default 'now')
        ToDate ........ string or int representing the last date for the chart 
                        (default '+5 days')
        MainWidth ..... approximate pixel width for the chart body (not including 
                        task names). The actual pixel width will vary, depending
                        on the other parameters (default 750).
                        You can optionally set a scrollable viewport to fit a 
                        wide display into a small screen by passing a string value 
                        in the form 'mainwidth>portwidth'; for example '1200>650' 
                        will create a 1200px width timeline, which is scrollable 
                        inside a 650px container.
        StepMinutes ... the number of minutes for each step in the interval between 
                        FromDate to ToDate (default 60)
        Headings ...... array with 2 elements; the date/time format for headings, 
                        and the number of minutes between headings.
                        eg array('H:i', 4*60) shows hr:min heading every 4 hours
                        (default false; no headings)
    Example: echo $cron->Chart('now', '+1 week');

->SetChartName - set the chart title
    Parameter: ChartName (default '')

->SetDateFormat - set the display format for dates
    Sets the format of displayed dates
        DateFormat .... format string compatible with PHP's date function, 
                        including year, month, day, hour and minute.
                        (default 'j M Y H:i')

->SetTaskNames - set friendly names for tasks
    Set a name for each task, based on a unique part of the command (or 
    in fact the entire crontab line). You can also set the name for a 
    specific task number by specifying its index. Without names set, 
    tasks will be called Task 1, Task 2, etc
        Names ......... an array of names, indexed by id or search string 
                        (default empty array)
    Example: $cron->SetTaskNames( array('twzFW.php'=>'FileWatch', 3=>'Third task') );

->SetTaskDurations - set estimated duration for tasks
    For tasks that take a long time to run, you can specify the estimated 
    duration and this will be indicated on the chart.
        Times ......... an array of times, indexed by id or search string
                        (similar to the SetTaskNames() parameter). 
                        Values can be minutes (int or string), or a string 
                        specifying hours and minutes
    Example: $cron->SetTaskDurations( array('twzFW.php'=>'12', 3=>'1:20') );

->GetNextRun - get the date of the next run for a task
->GetLastRun - get the date of the previous run for a task
    These methods return a string containing the next/previous scheduled run 
    date for a specific task, or false on error.
        Task ......... The name or numeric Id of the task to query (required)
        FromDate ..... The date from which to start searching (default 'now')
    Example: $NextDate = $cron->GetNextRun(2);

->GetTaskNames - get task names
    Returns an array of task names indexed by TaskId
    Parameters: none
    Example: $Tasks=$cron->GetTaskNames(); print_r($Tasks);

->GetTaskCrons - get cron line for all tasks
    Returns an array of task cron lines indexed by TaskId
    Parameters: none
    Example: $Tasks=$cron->GetTaskCrons(); print_r($Tasks);

->GetMailto - get cron mailto address
    If an email address was set in the crontab, this method returns it.
    Parameters: none

->GetErrors - get list of any errors
    Returns an array of any errors encountered.
    Parameters: none

->SetSwitchLimit - choose searching algorithm (ADVANCED)
    Sets the value of SwitchLimit to determine which search algorithm to use 
    when creating a Chart. When building the chart, twzCronChart steps from 
    FromDate to ToDate in units of StepMinutes (see Chart method). When 
    StepMinutes is more than 1 (ie almost always), there's a possibility that 
    we step over the exact time of a scheduled run. Therefore for each step, 
    twzCronChart needs to see if a scheduled run has been missed. There are two 
    different algorithms for doing this.
    (1) The first method steps back in time by 1 minute increments, checking 
        each time in turn. This method is efficient for smaller intervals.
    (2) The second method uses GetLastRun() - it finds the latest run date 
        prior to the current step, then checks if it's after the previous step. 
        This is more efficient for larger intervals.
    Which algorithm is used depends on the number of seconds between steps,
    and the choice is determined  by the value of SwitchLimit. The best value 
    to use can depend on various things, including the Chart interval and step,
    as well as the nature of the crontab. Let me know if you find a formula for 
    setting the best SwitchLimit! I think 60 times the chart StepMinutes (ie 
    StepMinutes converted to seconds) seems to work well most of the time.

        SwitchLimit ..... SwitchLimit in seconds (default 60*60*24 = 1 day)
        LogSwitchLimit .. If true, twzCronChart will populate the Errors array 
                          with the decision made for each step, and the total 
                          elapsed time to build the chart. This information can 
                          be retrieved from $cron->GetErrors() and you can use 
                          it for fine-tuning the SwitchLimit. (default false)


4. CSS class names

twzCronChart adds a number of class names to the HTML elements it generates. 
These class names can be used to style the chart to suit your preferences.
See the included example script for some ideas. The main classes of interest 
    .sched - when a task starts
    .sched span.inprog - while a task is in progress (see SetTaskDurations)
    .sched span.mon - start of new month
    .sched - start of new day
    .sched span.hour - start of new hour
    .sched - current date/time
If you don't want any special styling for any of these, remove them from your 
stylesheet or set their style the same as the default .sched span


5. Limitations

For people with only a few cron tasks, each with a simple schedule (ie people 
like me), twzCronChart will handle everything you throw at it. However with
a large number of tasks and/or a long charting period, it's likely to
struggle a bit. The SetSwitchLimit() method can be used to tweak performance
to some extent.

NOTE: Wikipedia gives two conflicting versions of how Day and Weekday values are
treated (Aug 2011). The "cron" article says that if both of these are specified,
then either one can match. For example day=3 with weekday=1 will match the 
3rd day of every month and every Monday, even if it's not Monday the 3rd. 

In contrast, the "CRON expression" article says it's not valid to specify 
both, and you should use a ? character for one of them. The latter article 
also mentions two additional fields: Seconds (mandatory) and Year (optional), 
as well as special characters L, W and #. 

We have assumed (from some reading of wiki talk pages) that "CRON expression" 
is more of a cron extension used elsewhere, but not by cron itself. Therefore
we have used the "cron" article, and ignored "CRON expression".