Config::Crontab(3) Read/Write Vixie compatible crontab(5) files

SYNOPSIS


use Config::Crontab;
####################################
## making a new crontab from scratch
####################################
my $ct = new Config::Crontab;
## make a new Block object
my $block = new Config::Crontab::Block( -data => <<_BLOCK_ );
## mail something to joe at 5 after midnight on Fridays
MAILTO=joe
5 0 * * Fri /bin/someprogram 2>&1
_BLOCK_
## add this block to the crontab object
$ct->last($block);
## make another block using Block methods
$block = new Config::Crontab::Block;
$block->last( new Config::Crontab::Comment( -data => '## do backups' ) );
$block->last( new Config::Crontab::Env( -name => 'MAILTO', -value => 'bob' ) );
$block->last( new Config::Crontab::Event( -minute => 40,
-hour => 3,
-command => '/sbin/backup --partition=all' ) );
## add this block to crontab file
$ct->last($block);
## write out crontab file
$ct->write;
###############################
## changing an existing crontab
###############################
my $ct = new Config::Crontab; $ct->read;
## comment out the command that runs our backup
$_->active(0) for $ct->select(-command_re => '/sbin/backup');
## save our crontab again
$ct->write;
###############################
## read joe's crontab (must have root permissions)
###############################
## same as "crontab -u joe -l"
my $ct = new Config::Crontab( -owner => 'joe' );
$ct->read;

DESCRIPTION

Config::Crontab provides an object-oriented interface to Vixie-style crontab(5) files for Perl.

A Config::Crontab object allows you to manipulate an ordered set of Event, Env, or Comment objects (also included with this package). Descriptions of these packages may be found below.

In short, Config::Crontab reads and writes crontab(5) files (and does a little pretty-printing too) using objects. The general idea is that you create a Config::Crontab object and associate it with a file (if unassociated, it will work over a pipe to "crontab -l"). From there, you can add lines to your crontab object, change existing line attributes, and write everything back to file.

  • NOTE: Config::Crontab does not (currently) do validity checks on your data (i.e., dates out of range, etc.). However, if the call to crontab fails when you invoke write, write will return undef and set error with the error message returned from the crontab command. Future development may tend toward more validity checks.

Now, to successfully navigate the module's ins and outs, we'll need a little terminology lesson.

Terminology

Config::Crontab (hereafter simply Crontab) sees a "crontab" file in terms of blocks. A block is simply an ordered set of one or more lines. Blocks are separated by two or more newlines. For example, here is a crontab file with two blocks:

    ## a comment
    30 4 * * * /bin/some_command
    
    ## another comment
    ENV=some_value
    50 9 * * 1-5 /bin/reminder --meeting=friday

The first block contains two Config::Crontab::* objects: a Comment object and an Event object. The second block contains an Env object in addition to a Comment object and an Event object. The Config::Crontab class, then, consists of zero or more Config::Crontab::Block objects. Block objects have these three basic elements:

Config::Crontab::Event
Any lines in a crontab that look like these are Event objects:

    5 10 * * * /some/command
    @reboot /bin/mystartup.sh
    ## 0 0 * * Fri /disabled/command

Notice that commented out event lines are still considered Event objects.

Event objects are described below in the Event package description. Please refer to it for details on manipulating Event objects.

Config::Crontab::Env
Any lines in a crontab that look like these are Env objects:

    MAILTO=joe
    SOMEVAR = some_value
    #DISABLED=env_setting

Notice that commented out environment lines are still considered Env objects.

Env objects are described below in the Env package description. Please refer to it for details on manipulating Env objects.

Config::Crontab::Comment
Any lines containing only whitespace or lines beginning with a pound sign (but are not Event or Env objects) are Comment objects:

    ## this is a comment
    (imagine somewhitespace here)

Comment objects are described below in the Comment package description. Please refer to it for details on manipulating Comment objects.

Illustration

Here is a simple crontab file:

  [email protected]
  ## send reminder in April
  3 10 * Apr Fri  joe  echo "Friday a.m. in April"

The file consists of an environment variable setting (MAILTO), a comment, and a command to run. After parsing the above file, Config::Crontab would break it up into the following objects:

    +---------------------------------------------------------+
    |     Config::Crontab object                              |
    |                                                         |
    |  +---------------------------------------------------+  |
    |  |      Config::Crontab::Block object                |  |
    |  |                                                   |  |
    |  |  +---------------------------------------------+  |  |
    |  |  |       Config::Crontab::Env object           |  |  |
    |  |  |                                             |  |  |
    |  |  |  -name => MAILTO                            |  |  |
    |  |  |  -value => [email protected]                   |  |  |
    |  |  |  -data => [email protected]             |  |  |
    |  |  +---------------------------------------------+  |  |
    |  +---------------------------------------------------+  |
    |                                                         |
    |  +---------------------------------------------------+  |
    |  |      Config::Crontab::Block object                |  |
    |  |                                                   |  |
    |  |  +---------------------------------------------+  |  |
    |  |  |       Config::Crontab::Comment object       |  |  |
    |  |  |                                             |  |  |
    |  |  |  -data => ## send reminder in April         |  |  |
    |  |  +---------------------------------------------+  |  |
    |  |                                                   |  |
    |  |  +---------------------------------------------+  |  |
    |  |  |       Config::Crontab::Event Object         |  |  |
    |  |  |                                             |  |  |
    |  |  |  -datetime => 3 10 * Apr Fri                |  |  |
    |  |  |  -special => (empty)                        |  |  |
    |  |  |  -minute => 3                               |  |  |
    |  |  |  -hour => 10                                |  |  |
    |  |  |  -dom => *                                  |  |  |
    |  |  |  -month => Apr                              |  |  |
    |  |  |  -dow => Fri                                |  |  |
    |  |  |  -user => joe                               |  |  |
    |  |  |  -command => echo "Friday a.m. in April"    |  |  |
    |  |  +---------------------------------------------+  |  |
    |  +---------------------------------------------------+  |
    +---------------------------------------------------------+

You'll notice the main Config::Crontab object encapsulates the entire file. The parser found two Block objects: the lone MAILTO variable setting, and the comment and command (together). Two or more newlines together in a crontab file constitute a block separator. This allows you to logically group commands (as most people do anyway) in the crontab file, and work with them as a Config::Crontab::Block objects.

The second block consists of a Comment object and an Event object, shown are some of the data methods you can use to get or set data in those objects.

Practical Usage: A Brief Tutorial

Now that we know what Config::Crontab objects look like and what they're called, let's play around a little.

Let's say we have an existing crontab on many machines that we want to manage. The crontab contains some machine-dependent information (e.g., timezone, etc.), so we can't just copy a file out everywhere and replace the existing crontab. We need to edit each crontab individually, specifically, we need to change the time when a particular job runs:

    30 2 * * * /usr/local/sbin/pirate --arg=matey

to 3:30 am because of daylight saving time (i.e., we don't want this job to run twice).

We can do something like this:

    use Config::Crontab;
    my $ct = new Config::Crontab;
    $ct->read;
    my ($event) = $ct->select(-command_re => 'pirate --arg=matey');
    $event->hour(3);
    $ct->write;

All done! This shows us a couple of subtle but important points:

  • The Config::Crontab object must have its read method invoked for it to read the crontab file.
  • The select method returns a list, even if there is only one item to return. This is why we put parentheses around $event (otherwise we would be putting the return value of select into scalar context and we would get the number of items in the list instead of the list itself).
  • The set methods for Event (and other) objects are usually invoked the same way as their get method except with an argument.
  • We must write the crontab back out to file with the write method.

Here's how we might do the same thing in a one-line Perl program:

    perl -MConfig::Crontab -e '$ct=new Config::Crontab; $ct->read; \
    ($ct->select(-command_re=>"pirate --arg=matey"))[0]->hour(3); \
    $ct->write'

Nice! Ok. Now we need to add a new crontab entry:

    35 6 * * * /bin/alarmclock --ring

We can do it like this:

    $event = new Config::Crontab::Event( -minute  => 36,
                                         -hour    => 6,
                                         -command => '/bin/alarmclock --ring');
    $block = new Config::Crontab::Block;
    $block->last($event);
    $ct->last($block);

or like this:

    $event = new Config::Crontab::Event( -data => '35 6 * * * /bin/alarmclock --ring' );
    $ct->last(new Config::Crontab::Block( -lines => [$event] ));

or like this:

    $ct->last(new Config::Crontab::Block(-data => "35 6 * * * /bin/alarmclock --ring"));

We learn the following things from this example:

  • Only Block objects can be added to Crontab objects (see ``CAVEATS''). Block objects may be added via the last method (and several other methods, including first, up, down, before, and after).
  • Block objects can be populated in a variety of ways, including the -data attribute (a string which may---and frequently does---span multiple lines via a 'here' document), the -lines attribute (which takes a list reference), and the last method. In addition to the last method, Block objects use the same methods for adding and moving objects that the Crontab object does: first, last, up, down, before, and after.

After the Module Utility section, the remainder of this document is a reference manual and describes the methods available (and how to use them) in each of the 5 classes: Config::Crontab, Config::Crontab::Block, Config::Crontab::Event, Config::Crontab::Env, and Config::Crontab::Comment. The reader is also encouraged to look at the example CGI script in the eg directory and the (somewhat contrived) examples in the t (testing) directory with this distribution.

Module Utility

Config::Crontab is a useful module by virtue of the ``one-liner'' test. A useful module must do useful work (editing crontabs is useful work) economically (i.e., useful work must be able to be done on a single command-line that doesn't wrap more than twice and can be understood by an adept Perl programmer).

Graham Barr's Net::POP3 module (actually, most of Graham's work falls in this category) is a good example of a useful module.

So, with no more ado, here are some useful one-liners with Config::Crontab:

  • uncomment all crontab events whose command contains the string 'fetchmail'

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $_->active(1) for $c->select(-command_re => "fetchmail"); $c->write'
    
  • remove the first crontab block that has '/bin/unwanted' as a command

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $c->remove($c->block($c->select(-command_re => "/bin/unwanted"))); \
      $c->write'
    
  • reschedule the backups to run just Monday thru Friday:

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $_->dow("1-5") for $c->select(-command_re => "/sbin/backup"); $c->write'
    
  • reschedule the backups to run weekends too:

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $_->dow("*") for $c->select(-command_re => "/sbin/backup"); $c->write'
    
  • change all 'MAILTO' environment settings in this crontab to '[email protected]':

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $_->value([email protected]!) for $c->select(-name => "MAILTO"); $c->write'
    
  • strip all comments from a crontab:

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $c->remove($c->select(-type => "comment")); $c->write'
    
  • disable an entire block of commands (the block that has the word 'Friday' in it):

      perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
      $c->block($c->select(-data_re => "Friday"))->active(0); $c->write'
    
  • copy one user's crontab to another user:

      perl -MConfig::Crontab -e '$c = new Config::Crontab(-owner => "joe"); \
      $c->read; $c->owner("mike"); $c->write'
    

PACKAGE Config::Crontab

This section describes Config::Crontab objects (hereafter simply Crontab objects). A Crontab object is an abstracted way of dealing with an entire crontab(5) file. The Crontab class has methods to allow you to select, add, or remove Block objects as well as read and parse crontab files and write crontab files.

init([%args])

This method is called implicitly when you instantiate an object via new. init takes the same arguments as new and read. If the -file argument is specified (and is non-false), init will invoke read automatically with the -file value. Use init to re-initialize an object.

Example:

    ## auto-parses foo.txt in implicit call to init
    $ct = new Config::Crontab( -file => 'foo.txt' );
    ## re-initialize the object with default values and a new file
    $ct->init( -file => 'bar.txt' );

strict([boolean])

strict enforces the following constraints:
  • if the file specified by the file method (or -file attribute in new) does not exist at the time read is invoked, read sets error and dies: ``Could not open (filename): (reason)''. If strict is disabled, read returns undef (error is set).
  • If the file specified by the file method (or -file attribute in new) cannot be written to, or the "crontab" command fails, write sets error and warns: ``Could not open (filename): (reason)''. If strict is disabled, write returns undef (error is set).
  • Croaks if an illegal username is specified in the -owner parameter.

Examples:

    ## disable strict (default)
    $ct->strict(0);

system([boolean])

system tells config::crontab to assume that the crontab object is after the pattern described in crontab(5) with an extra user field before the command field:

  @reboot     joeuser    /usr/local/bin/fetchmail -d 300

where the given command will be executed by said user. when a crontab file (e.g., /etc/crontab) is parsed without system enabled, the user field will be lumped in with the command. When enabled, the user field will be accessible in each event object via the user method (see ``user'' in the event documentation below).

owner([string])

owner sets the owner of the crontab. If you're running Config::Crontab as a privileged user (e.g., ``root''), you can read and write user crontabs by specifying owner either in the constructor, during init, or using owner before a read or write method is called:

  $c = new Config::Crontab( -owner => 'joe' );
  $c->read;  ## reading joe's crontab

Or another way:

  $c = new Config::Crontab;
  $c->owner('joe');
  $c->read;  ## reading joe's crontab

You can use this to copy a crontab from one user to another:

  $c->owner('joe');
  $c->read;
  $c->owner('bob');
  $c->write;

owner_re([regex])

Config::Crontab is strict in what it will allow for a username, since this information internally is passed to a shell. If the username specified is not a user on the system, Config::Crontab will set error with ``Illegal username'' and return undef; if strict mode is enabled, Config::Crontab will croak with the same error.

Further, once the username is determined valid, the username is then checked against a regular expression to thwart null string attacks and other maliciousness. The default regular expression used to check for a safe username is:

    /[^a-zA-Z0-9\._-]/

If the pattern matches (i.e., if any characters other than the ones above are found in the supplied username), Config::Crontab will set error with ``Illegal username'' and return undef. If strict mode is enabled, Config::Crontab will croak with the same error.

  $c->owner_re('[^a-zA-Z0-9_\.-#]');  ## allow # in usernames

read([%args])

Parses the crontab file specified by file. If file is not set (or is false in some way), the crontab will be read from a pipe to "crontab -l". read optionally takes the same arguments as new and init in "key => value" style lists.

Until you read the crontab, the Crontab object will be uninitialized and will contain no data. You may re-read existing objects to get new crontab data, but the object will retain whatever other attributes (e.g., strict, etc.) it may have from when it was initialized (or later attributes were changed) but will reset error. Use init to completely refresh an object.

If read fails, error will be set.

Examples:

    ## reads the crontab for this UID (via crontab -l)
    $ct = new Config::Crontab;
    $ct->read;
    ## reads the crontab from a file
    $ct = new Config::Crontab;
    $ct->read( -file => '/var/cronbackups/cron1' );
    ## same thing as above
    $ct = new Config::Crontab( -file => '/var/cronbackups/cron1' );
    $ct->read; ## '-file' attribute already set
    ## ditto using 'file' method
    $ct = new Config::Crontab;
    $ct->file('/var/cronbackups/cron1');
    $ct->read;
    ## ditto, using a pipe
    $ct = new Config::Crontab;
    $ct->file('cat /var/cronbackups/cron1|');
    $ct->read;
    ## ditto, using 'read' method
    $ct = new Config::Crontab;
    $ct->read( -file => 'cat /var/cronbackups/cron1|');
    ## now fortified with error-checking
    $ct->read
      or do {
        warn $ct->error;
        return;
      };

mode([mode])

Returns the current parsing mode for this object instance. If a mode is passed as an argument, next time this instance parses a crontab file, it will use this new mode. Valid modes are line, block (the default), or file.

Example:

    ## re-read this crontab in 'file' mode
    $ct->mode('file');
    $ct->read;

blocks([\@blocks])

Returns a list of Block objects in this crontab. The blocks method also takes an optional list reference as an argument to set this crontab's block list.

Example:

    ## get blocks, remove comments and dump
    for my $block ( $ct->blocks ) {
        $block->remove($block->select( -type   => 'comment' ) );
        $block->remove($block->select( -type   => 'event',
                                       -active => 0 );
        print $block->dump;
    }
    ## one way to remove unwanted blocks from a crontab
    my @keepers = $ct->select( -type    => 'comment',
                               -data_re => 'keep this block' );
    $ct->blocks(\@keepers);
    ## another way to do it (notice 'nre' instead of 're')
    $ct->remove($ct->select( -type     => 'comment',
                             -data_nre => 'keep this block' ));

select([%criteria])

Returns a list of crontab lines that match the specified criteria. Multiple criteria may be specified. If no criteria are specified, select returns a list of all lines in the Crontab object.

Field names should be preceded by a hyphen (though without a hyphen is acceptable too).

The following criteria and associated values are available:

  • -type

    One of 'event', 'env', or 'comment'

  • -<field>

    The object in the block will be matched using 'eq' (string comparison) against this criterion.

  • -<field>_re

    The value of the object method specified will be matched using Perl regular expressions (see perlre) instead of string comparisons (uses the "=~" operator internally).

  • -<field>_nre

    The value of the object method specified will be negatively matched using Perl regular expressions (see perlre) instead of string comparisons (uses the "!~" operator internally).

Examples:

    ## returns a list of comments in the crontab that matches the
    ## exact phrase '## I like bread'
    @comments = $ct->select( -type => 'comment',
                             -data => '## I like bread' );
    ## returns a list of comments in the crontab that match the
    ## regular expression 'I like bread'
    @comments = $ct->select( -type    => 'comment', 
                             -data_re => 'I like bread' );
    ## select all cron jobs likely to repeat during daylight saving
    @events = $ct->select( -type => 'event',
                           -hour => '2' );
    ## select cron jobs that happen from 10:20 to 10:40 on Fridays
    @events = $ct->select( -type      => 'event',
                           -hour      => '10',
                           -minute_re => '^(?:[2-3][0-9]|40)$',
                           -dow_re    => '(?:5|Fri)' );
    ## select all cron jobs that execute during business hours
    @events = $ct->select( -type    => 'event',
                           -hour_re => '^(?:[8-9]|1[0-6])$' );
    ## select all cron jobs that don't execute during business hours
    @events = $ct->select( -type     => 'event',
                           -hour_nre => '^(?:[8-9]|1[0-6])$' );
    ## get all event lines in the crontab
    @events = $ct->select( -type => 'event' );
    ## get all lines in the crontab
    @lines => $ct->select;
    ## get a line: note list context, also, no 'type' specified
    ($line) = $ct->select( -data_re => 'start backups' );

select_blocks([%criteria])

Returns a list of crontab Block objects that match the specified criteria. If no criteria are specified, select_blocks behaves just like the blocks method, returning all blocks in the crontab object.

The following criteria keys are available:

  • -index

    An integer or list reference of integers. Returns a list of blocks indexed by the given integer(s).

    Example:

      ## select the first block in the file
      @blocks = $ct->select_blocks( -index => 1 );
      ## select blocks 1, 5, 6, and 7
      @blocks = $ct->select_blocks( -index => [1, 5, 6, 7] );
    

select_blocks returns Block objects, which means that if you need to access data elements inside the blocks, you'll need to retrieve them using lines or select method first:

  ## the first block in the crontab file is an environment variable
  ## declaration: NAME=value
  @blocks = $ct->select_blocks( -index => 1 );
  print "This environment variable value is " . ($block[0]->lines)[0]->value . "\n";

block($line)

Returns the block that this line belongs to. If the line is not found in any blocks, undef is returned. $line must be a Config::Crontab::Event, Config::Crontab::Env, or Config::Crontab::Comment object.

Examples:

    ## will always return undef for new objects; you'd never really do this
    $block = $ct->block( new Config::Crontab::Comment(-data => '## foo') );
    ## returns a Block object
    $block = $ct->block($existing_crontab_line);
    $block->dump;
    ## find and remove the block in which '/bin/baz' is executed
    my $event = $ct->select( -type       => 'event',
                             -command_re => '/bin/baz');
    $block = $ct->block($event);
    $ct->remove($block);

remove($block)

Removes a block from the crontab file (if a block is specified) or a crontab line from its block (if a crontab line object is specified).

Example:

    ## remove this block from the crontab
    $ct->remove($block);
    ## remove just a line from its block
    $ct->remove($line);

replace($oldblock, $newblock)

Replaces $oldblock with $newblock. Returns $oldblock if successful, undef otherwise.

Example:

    ## look for the block containing 'oldtuesday' and replace it with our new block
    $newblock = new Config::Crontab::Block( -data => '5 10 * * Tue /bin/tuesday' );
    my $oldblock = $ct->block($ct->select(-data_re => 'oldtuesday'));
    $ct->replace($oldblock, $newblock);

up($block), down($block)

These methods move a single Config::Crontab::Block object up or down in the Crontab object's internal array. If the Block object is not already a member of this array, it will be added to the array in the first position (for up) and in the last position (for down. See also first and last and up and down in the Block class.

Example:

    $ct->up($block);  ## move this block up one position

first(@block), last(@block)

These methods move the Config::Crontab::Block object(s) to the first or last positions in the Crontab object's internal array. If the block is not already a member of the array, it will be added in the first or last position respectively.

Example:

    $ct->last(new Config::Crontab::Block( -data => <<_BLOCK_ ));
    ## eat ice cream
    5 * * * 1-5 /bin/eat --cream=ice
    _BLOCK_

before($look_for, @blocks), after($look_for, @blocks)

These methods move the Config::Crontab::Block object(s) to the position immediately before or after the $look_for (or reference) block in the Crontab object's internal array.

If the objects are not members of the array, they will be added before or after the reference block respectively. If the reference object does not exist in the array, the blocks will be moved (or added) to the beginning or end of the array respectively (like first and last).

Example:

    ## search for a block containing a particular event (line)
    $block = $ct->block($ct->select(-command_re => '/bin/foo'));
    ## add the new blocks immediately after this block
    $ct->after($block, @new_blocks);

write([$filename])

Writes the crontab to the file specified by the file method. If file is not set (or is false), write will attempt to write to a temporary file and load it via the "crontab" program (e.g., "crontab filename").

You may specify an optional filename as an argument to set file, which will then be used as the filename.

If write fails, error will be set.

Example:

    ## write out crontab
    $ct->write
      or do {
        warn "Error: " . $ct->error . "\n";
        return;
      };
    ## set 'file' and write simultaneously (future calls to read and
    ## write will use this filename)
    $ct->write('/var/mycronbackups/cron1.txt');
    ## same thing
    $ct->file('/var/mycronbackups/cron1.txt');
    $ct->write;

remove_tab([file])

Removes a crontab. If file is set, that file will be unlinked. If file is not set (or is false), remove_tab will attempt to remove the selected user's crontab via crontab -u username -r or crontab -r for the current user id.

If remove_tab fails, error will be set.

Example:

  $ct->remove_tab('');  ## unset file() and remove the current user's crontab

error([string])

Returns the last error encountered (usually during a file I/O operation). Pass an empty string to reset (calling init will also reset it).

Example:

    print "The last error was: " . $ct->error . "\n";
    $ct->error('');

dump

Returns a string containing the crontab file.

Example:

    ## show crontab
    print $ct->dump;
    ## same as 'crontab -l' except pretty-printed
    $ct = new Config::Crontab; $ct->read; print $ct->dump;

PACKAGE Config::Crontab::Block

This section describes Config::Crontab::Block objects (hereafter referred to as Block objects). A Block object is an abstracted way of dealing with groups of crontab(5) lines. Depending on how Config::Crontab parsed the file (see the read and mode methods in Config::Crontab above), a block may consist of:
a single line (e.g., a crontab event, environment setting, or comment)
a "paragraph" of lines (a group of lines, each group separated by at least two newlines). This is the default parsing mode.
the entire crontab file

The default for Config::Crontab is to read in block (paragraph) mode. This allows you to group lines that have a similar purpose as well as order lines within a block (e.g., often you want an environment setting to take effect before certain cron commands execute).

An illustration may be helpful:

a crontab file read in block (paragraph) mode:
    Line     Block    Block Line    Entry
    1        1        1             ## grind disks
    2        1        2             5 5 * * * /bin/grind
    3        1        3
    4        2        1             ## backup reminder to joe
    5        2        2             MAILTO=joe
    6        2        3             5 0 * * Fri /bin/backup
    7        2        4
    8        3        1             ## meeting reminder to bob
    9        3        2             MAILTO=bob
    10       3        3             30 9 * * Wed /bin/meeting

Notice that each block has its own internal line numbering. Vertical space has been inserted between blocks to clarify block structures. Block mode parsing is the default.

a crontab file read in line mode:
    Line     Block    Block Line    Entry
    1        1        1             ## grind disks
    2        2        1             5 5 * * * /bin/grind
    3        3        1
    4        4        1             ## backup reminder to joe
    5        5        1             MAILTO=joe
    6        6        1             5 0 * * Fri /bin/backup
    7        7        1
    8        8        1             ## meeting reminder to bob
    9        9        1             MAILTO=bob
    10       10       1             30 9 * * Wed /bin/meeting

Notice that each line is also a block. You normally don't want to read in line mode unless you don't have paragraph breaks in your crontab file (the dumper prints a newline between each block; with each line being a block you get an extra newline between each line).

a crontab file read in file mode:
    Line     Block    Block Line    Entry
    1        1        1             ## grind disks
    2        1        2             5 5 * * * /bin/grind
    3        1        3
    4        1        4             ## backup reminder to joe
    5        1        5             MAILTO=joe
    6        1        6             5 0 * * Fri /bin/backup
    7        1        7
    8        1        8             ## meeting reminder to bob
    9        1        9             MAILTO=bob
    10       1        10            30 9 * * Wed /bin/meeting

Notice that there is only one block in file mode, and each line is a block line (but not a separate block).

METHODS

This section describes methods accessible from Block objects.

new([%args])

Creates a new Block object. You may create Block objects in any of the following ways:
Empty
    $event = new Config::Crontab::Block;
Fully Populated
    $event = new Config::Crontab::Block( -data => <<_BLOCK_ );
    ## a comment
    5 19 * * Mon /bin/fhe --turn=dad
    _BLOCK_

Constructor attributes available in the new method take the same arguments as their method counterparts (described below), except that the names of the attributes must have a hyphen ('-') prepended to the attribute name (e.g., 'lines' becomes '-lines'). The following is a list of attributes available to the new method:

data
lines

If the -data attribute is present in the constructor when other attributes are also present, the -data attribute will override all other attributes.

Each of these attributes corresponds directly to its similarly-named method.

Examples:

    ## create an empty block object & populate it with the data method
    $block = new Config::Crontab::Block;
    $block->data( <<_BLOCK_ );  ## via a 'here' document
    ## 2:05a Friday backup
    [email protected]
    5 2 * * Fri /sbin/backup /dev/da0s1f
    _BLOCK_
    ## create a block in the constructor (also via 'here' document)
    $block = new Config::Crontab::Block( -data => <<_BLOCK_ );
    ## 2:05a Friday backup
    [email protected]
    5 2 * * Fri /sbin/backup /dev/da0s1f
    _BLOCK_
    ## create an array of crontab objects
    my @lines = ( new Config::Crontab::Comment(-data => '## run bar'),
                  new Config::Crontab::Event(-data => '5 8 * * * /foo/bar') );
    ## create a block object via lines attribute
    $block = new Config::Crontab::Block( -lines => \@lines );
    ## ...or with lines method
    $block->lines(\@lines);  ## @lines is an array of crontab objects

If bogus data is passed to the constructor, it will return undef instead of an object reference. If there is a possiblility of poorly formatted data going into the constructor, you should check the object variable for definedness before using it.

If the -data attribute is present in the constructor when other attributes are also present, the -data attribute will override all other attributes.

data([string])

Get or set a raw block. Internally, Block passes its arguments to other objects for parsing when a parameter is present.

Example:

    ## re-initialize this block
    $block->data("## comment\n5 * * * * /bin/checkup");
    print $block->data;

Block data is terminated with a final newline.

lines([\@objects])

Get block data as a list of Config::Crontab::* objects. Set block data using a list reference.

Example:

    $block->lines( [ new Config::Crontab::Comment( -data => "## run backup" ),
                     new Config::Crontab::Event( -data => "5 4 * * 1-5 /sbin/backup" ) ] );
    ## sorta like $block->dump
    for my $obj ( $block->lines ) {
        print $obj->dump . "\n";
    }
    ## a clumsy way to "unshift" a new event
    $block->lines( [new Config::Crontab::Comment(-data => '## hi mom!'),
                    $block->lines] );
    ## the right way to add a new event
    $block->first( new Config::Crontab::Comment(-data => '## hi mom!') );
    print $_->dump for $block->lines;

select([%criteria])

Returns a list of Event, Env, or Comment objects from a block that match the specified criteria. Multiple criteria may be specified.

Field names should be preceded by a hyphen (though without a hyphen is acceptable too; we use hyphens to avoid the need for quoting keys and avoid potential bareword collisions).

If not criteria are specified, select returns a list of all lines in the block (like lines).

Example:

    ## select all events
    for my $event ( $block->select( -type => 'event') ) {
        print $event->dump . "\n";
    }
    ## select events that have the word 'foo' in the command
    for my $event ( $block->select( -type => 'event', -command_re => 'foo') ) {
        print $event->dump . "\n";
    }

remove(@objects)

Remove Config::Crontab::* objects from this block.

Example:

    ## simple case: you need to get a handle on these objects first
    $block->remove( $obj1, $obj2, $obj3 );
    ## more complex: remove an event from a block by searching
    for my $event ( $block->select( -type => 'event') ) {
        next unless $event->command =~ /\bbackup\b/;  ## look for backup command
        $block->remove($event); last;  ## and remove it
    }

replace($oldobj, $newobj)

Replaces $oldobj with $newobj within a block. Returns $oldobj if successful, undef otherwise.

Example:

    ## replace $event1 with $event2 in this block.
    ## '=>' is the same as a comma (,)
    ($event1) = $block->select(-type => 'event', -command => '/bin/foo');
    $event2 = new Config::Crontab::Event( -data => '5 2 * * * /bin/bar' );
    ok( $block->replace($event1 => $event2) );

up($target_obj), down($target_obj)

These methods move the Config::Crontab::* object up or down within the block.

If the object is not a member of the block, it will be added to the block in the first position for up and it will be added to the block in the last position for down.

Examples:

    $block->up($event);  ## move event up one position in the block
    ## add a new event at the end of the block
    $block->down(new Config::Crontab::Event(-data => '5 2 * * Mon /bin/monday'));

first(@target_obj), last(@target_obj)

These methods move the Config::Crontab::* object(s) to the first or last positions in the block.

If the object or objects are not members of the block, they will be added to the first or last part of the block respectively.

Examples:

    $block->first($comment);  ## move $comment to the first line in this block
    ## add these new events to the end of the block
    $block->last( new Config::Crontab::Comment(-data => '## hi mom!'),
                  new Config::Crontab::Comment(-data => '## hi dad!'), );

before($look_for, @obj), after($look_for, @obj)

These methods move the Config::Crontab::* object(s) to the position immediately before or after the $look_for (or reference) object in the block.

If the objects are not members of the block, they will be added to the block before or after the reference object. If the reference object does not exist in the block, the objects will be moved (or added) to the beginning or end of the block respectively (much the same as first and last).

    ## simple example
    $block->after($event, $comment);  ## move $comment after $event in this block

active(boolean)

Activates or deactivates an entire block. If no arguments are given, active returns true but does nothing, otherwise the boolean used to activate or deactivate the block is returned.

If you have a series of related crontab lines you wish to comment out (or uncomment), you can use this handy shortcut to do it. You cannot deactivate Comment objects (i.e., they will always be comments).

Example:

    $block->active(0);  ## deactivate this block

nolog(boolean)

This is (currently) a SuSE-specific extension. From crontab(5):

  If the uid of the owner is 0 (root), he can put a "-" as first
  character of a crontab entry. This will prevent cron from writing a
  syslog message about this command getting executed.

nolog enables adds or removes this hyphen for a given cron event line (regardless of whether the user is root or not).

Example:

    $block->nolog(1);  ## quiet all entries in this block

flag(string)

Flags a block or an object inside a block with the specified data. The data you specify is completely up to you. This can be handy if you need to operate on many objects at once and don't want to risk pulling the rug out from under some (i.e., deleting numbered elements from a list changes the numbering of subsequent objects in the list, which is probably not what you want).

All normal query operations apply to -flag attributes (e.g., -flag_re, -flag_nre, etc).

Example:

    ## delete every other event in this block
    my $count = 0;
    for my $event ( $block->select( -type => 'event' ) ) {
        $event->flag('deleteme!')
          if $count % 2 == 0;
        $count++;
    }
    ## delete all blocks marked as 'deleteme!'
    $block->remove( $block->select( -flag => 'deleteme!' ) );

dump

Returns a formatted string of the Block object (recursively calling all its objects' dump methods). A Block dump is newline terminated.

Example:

    print $block->dump;

PACKAGE Config::Crontab::Event

This section describes Config::Crontab::Event objects (hereafter Event objects). A Event object is an abstracted way of dealing with crontab(5) lines that look like any of the following (see crontab(5)):
5 0 * 3,6,9,12 * /bin/quarterly_report
0 2 * * Fri $HOME/bin/cake_reminder
@daily /bin/bar arg1 arg2
#30 10 12 * * /bin/commented out
5 4 * * * joeuser /bin/winkerbean

Event objects are lines in the crontab file which trigger an event at a certain time (or set of times). This includes events that have been commented out. In Event object terms, an event that has been commented out is inactive. Events that have not been commented out are active.

Terminology

The following description will serve as a terminology guide for this class:

Given the following crontab event entry:

    5 3 * Apr Sun  /bin/rejoice

we define the following parts of the Event object:

    5 3 * Apr Sun  /bin/rejoice
    -------------  ------------
      datetime       command

We can break down the datetime field into the following parts:

     5      3     *    Apr   Sun
   ------  ----  ---  -----  ---
   minute  hour  dom  month  dow

We might also see an event with a ``special'' datetime part:

    @daily    /bin/brush --teeth --feet
    --------  -------------------------
    datetime          command

This special datetime field can also be called 'special':

    @daily   /bin/brush --teeth --feet
    -------  -------------------------
    special          command

As of version 1.05, Crontab supports system crontabs, which adds an extra user field:

    5 3 * Apr Sun  chris  /bin/rejoice
    -------------  -----  ------------
      datetime     user     command

This field is described in crontab(5) on most systems.

These and other methods for accessing and manipulating Event objects are described in subsequent sections.

METHODS

This section describes methods available to manipulate Event objects' creation and attributes.

new([%args])

Creates a new Event object. You may create Event objects in any of the following ways:
Empty
    $event = new Config::Crontab::Event;
Partially Populated
    $event = new Config::Crontab::Event( -minute => 0 );
Fully Populated
    $event = new Config::Crontab::Event( -minute  => 5,
                                         -hour    => 2,
                                         -command => '/bin/document my_proggie', );
System Event
    $event = new Config::Crontab::Event( -minute  => 5,
                                         -hour    => 2,
                                         -user    => 'joeuser',
                                         -command => '/bin/foo --bar=blech', );
System Event
    $event = new Config::Crontab::Event( -data   => '30 3 * * 5,6 joeuser /bin/blech',
                                         -system => 1, );

Constructor attributes available in the new method take the same arguments as their method counterparts (described below), except that the names of the attributes must have a hyphen ('-') prepended to the attribute name (e.g., 'month' becomes '-month'). The following is a list of attributes available to the new method:

-minute
-hour
-dom
-month
-dow
-special
-data
-datetime
-user
-system
-command
-active

Each of these attributes corresponds directly to its similarly-named method.

Examples:

    ## use datetime attribute; using a 'special' string in -datetime is
    ## ok, but the reverse is not true (using a standard datetime string
    ## in -special)
    $event = new Config::Crontab::Event( -datetime => '@hourly',
                                         -command  => '/bin/bar' );
    ## use special attribute
    $event = new Config::Crontab::Event( -special => '@hourly',
                                         -command => '/bin/bar' );
    ## use datetime attribute
    $event = new Config::Crontab::Event( -datetime => '5 * * * Fri',
                                         -command  => '/bin/bar' );
    ## this is an error because '5 * * * Fri' is not one of the special
    ## datetime strings. Currently this does not throw an error, but 
    ## behavior is undefined for an object initialized thusly
    $event = new Config::Crontab::Event( -special => '5 * * * Fri',
                                         -command => '/bin/bar' );
    ## create an inactive Event; default for datetime fields is '*'
    ## the result is the line: "#0 2 * * * /bin/foo" (notice '#')
    $event = new Config::Crontab::Event( -active   => 0,
                                         -minute   => 0,
                                         -hour     => 2,  ## 2 am
                                         -command  => '/bin/foo' );
    ...time passes...
    $event->active(1);  ## now activate that event
    ## let the object do all the hard parsing
    $event = new Config::Crontab::Event( -data => '30 3 * * 5,6 /bin/blech' );
    ...time passes...
    $event->hour(4);  ## change the event from 3:30a to 4:30a

If bogus data is passed to the constructor, it will return undef instead of an object reference. If there is a possiblility of poorly formatted data going into the constructor, you should check the object variable for definedness before using it.

A note about the datetime fields

Event objects have several ways of setting the datetime fields:

    ## via the special method
    $event->special('@daily');
    ## via datetime
    $event->datetime('@daily');
    ## via datetime
    $event->datetime('0 0 * * *');
    ## via datetime fields
    $event->minute(0);
    $event->hour(0);
    ## via data (takes the command part also)
    $event->data('0 0 * * * /bin/foo');
    ## via the constructor at object instantiation time
    $event = new Config::Crontab::Event( -special => '@reboot' );

The standard datetime fields are: minute, hour, dom, month, and dow. If you set datetime using a special field, or if you initialize an Event object using a special datetime field, the standard datetime fields are reset to '*' and are invalid.

The special datetime field is a single field that takes the place of the 5 standard datetime fields (see crontab(5) and ``special''). Currently, if you set special via the special method, the standard datetime fields (e.g., minute, hour, etc.) are not reset; the standard datetime fields are reset to '*' if you set special via the datetime method.

See other important information in the datetime and special method descriptions below.

If the -data attribute is present in the constructor when other attributes are also present, the -data attribute will override all other attributes.

minute([digits])

Get or set the minute attribute of the Event object.

Example:

    $event->minute(30);
    print "This event will occur at " . $event->minute . " minutes past the hour\n";
    $event->minute(40);
    print "Now it will occur 10 minutes later\n";

Note from crontab(5):

    Ranges of numbers are allowed.  Ranges are two numbers separated with a
    hyphen.  The specified range is inclusive.  For example, 8-11 for an
    ``hours'' entry specifies execution at hours 8, 9, 10 and 11.
    Lists are allowed.  A list is a set of numbers (or ranges) separated by
    commas.  Examples: ``1,2,5,9'', ``0-4,8-12''.
    Step values can be used in conjunction with ranges.  Following a range
    with ``/<number>'' specifies skips of the number's value through the
    range.  For example, ``0-23/2'' can be used in the hours field to specify
    command execution every other hour (the alternative in the V7 standard is
    ``0,2,4,6,8,10,12,14,16,18,20,22'').  Steps are also permitted after an
    asterisk, so if you want to say ``every two hours'', just use ``*/2''.

hour([digits])

Get or set the hour attribute of the Event object.

Example: analogous to minute

Note from crontab(5): see /``minute''.

dom([digits])

Get or set the day-of-month attribute of the Event object.

Example: analogous to minute

Note from crontab(5):

    Note: The day of a command's execution can be specified by two fields --
    day of month, and day of week.  If both fields are restricted (ie, aren't
    *), the command will be run when either field matches the current time.
    For example,
    ``30 4 1,15 * 5'' would cause a command to be run at 4:30 am on the 1st
    and 15th of each month, plus every Friday.

month([string])

Get or set the month. This may be a digit (1-12) or a three character English abbreviated month string (Jan, Feb, etc.).

Note from crontab(5):

    Names can also be used for the ``month'' and ``day of week'' fields.  Use
    the first three letters of the particular day or month (case doesn't mat-
    ter).  Ranges or lists of names are not allowed.

dow([string])

Get or set the day of week.

Example: analogous to minute

Note from crontab(5): see the /``month'' entry above.

special([string])

Get or set the special datetime field.

The special datetime field is one of (from crontab(5)):

    string          meaning
    ------          -------
    @reboot         Run once, at startup.
    @yearly         Run once a year, "0 0 1 1 *".
    @annually       (sames as @yearly)
    @monthly        Run once a month, "0 0 1 * *".
    @weekly         Run once a week, "0 0 * * 0".
    @daily          Run once a day, "0 0 * * *".
    @midnight       (same as @daily)
    @hourly         Run once an hour, "0 * * * *".

If you set a datetime via special, this will override anything in the other standard datetime fields.

While you may use a special datetime string as an argument to the datetime method, you may not use a standard datetime string in the special method. Currently there is no error checking on this field, but behavior is undefined.

The datetime method will return the special value in preference to any other standard datetime fields. That is, if special has a value (e.g., '@reboot', etc.) it will be returned in all methods that return aggregate event data (e.g., datetime, dump, data, etc.). If special is false, the standard datetime fields will be returned instead. Thus, you should always check the value of special before using any of the standard datetime fields:

    if( $event->special ) {
        print $event->special . "\n";
    }
    ## use standard datetime elements
    else {
        print $event->minute . " " . $event->hour ...
    }

If you're presenting the entire datetime field formatted, use the datetime method (and then you don't have to do any checks on special):

    ## will print the special datetime value if set,
    ## standard datetime fields otherwise
    print $event->datetime . "\n";

data([string])

Get or set the raw event line.

Internally, this is how the main Config::Crontab class does its parsing: it iterates over the crontab file and hands each line off to the data method for further parsing.

Example:

    $event->data("#0 2 * * * /bin/foo");
    ## prints "inactive (/bin/foo): 0 2 * * *";
    print ( $event->active ? '' : 'in' ) . 'active ' 
        . '(' . $event->command . '): " 
        . $event->datetime;

datetime([string])

Get or set the datetime fields of an event.

Possible datetime fields are either a special datetime format (e.g., @daily, @weekly, etc) or a standard datetime format (e.g., ``0 2 * * Mon'' is standard).

datetime is often a convenient shortcut for parsing a datetime field if you're not precisely sure what's in it (but are sure that it's either a special datetime field or a standard datetime field):

    $event->datetime($some_string);

While you may pass a special datetime field into datetime, you may not pass a standard field into the special method. Currently, the object will not complain, and may even work in most cases, but the behavior is undefined and will likely become more strict in the future.

user([string])

Get or set the user part of a system event object.

Example:

    $event->user('joeuser');

The user field is only accessible when the crontab object was created or parsed with system mode enabled (see ``system'' above).

system([boolean])

When set, will parse a -data string looking for a username before the command as described in crontab(5).

Example:

    $event->system(1);
    $event->data('0 2 * * * joeuser /bin/foo --args');

This will set the user as 'joeuser' and the command as '/bin/foo --args'. Notice that if you pass bad data, the Event parser really can't help since the user (including '/<login-class>') syntax is now supported as of version 1.05:

    $event = new Config::Crontab::Event( -data   => '2 5 * * * /bin/foo --args',
                                         -system => 1 );

The Event object will have '/bin/foo' as its user and '--args' as its command. While things will usually work out when you write to file, you definitely won't get what you're expecting if you grok the command field.

command([string])

Get or set the command part of a Event object.

Example:

    $event->command('/bin/foo with args here');

active([boolean])

Get or set whether the Event object is active. In practical terms, this simply inserts a pound sign before the datetime fields when accessing the dump method. It is only used implicitly in dump, but may be accessed separately whenever convenient.

    print ( $event->active ? '' : '#' ) . $event->data . "\n";

is the same as:

    print $event->dump . "\n";

dump

Returns a formatted string of the Event object. This method is called implicitly when flushing to disk in Config::Crontab. It is not newline terminated.

Example:

    print $event->dump . "\n";

PACKAGE Config::Crontab::Env

This section describes Config::Crontab::Env objects (hereafter Env objects). A Env object is an abstracted way of dealing with crontab lines that look like any of the following (see crontab(5)):

    name = value

From crontab(5):

    the spaces around the equal-sign (=) are optional, and any
    subsequent non-leading spaces in value will be part of the value
    assigned to name.  The value string may be placed in quotes
    (single or double, but matching) to preserve leading or trailing
    blanks.  The name string may also be placed in quote (single or
    double, but matching) to preserve leading, traling or inner
    blanks.

Like Event objects, Env objects may be active or inactive, the difference being an inactive Env object is commented out:

    #FOO=bar

Terminology

Given the following crontab environment line:

    MAILTO=joe

we define the following parts of the Env object:

    MAILTO        =        joe
    ======  ============  =====
     name   (not stored)  value

These and other methods for accessing and manipulating Event objects are described in subsequent sections.

METHODS

new([%args])

Creates a new Env object. You may create Env objects any of the following ways:
Empty
    $env = new Config::Crontab::Env;
Partially Populated
    $env = new Config::Crontab::Env( -value => 'joe' );
Fully Populated
    $env = new Config::Crontab::Env( -name  => 'FOO',
                                     -value => 'blech' );

Constructor attributes available in the new method take the same arguments as their method counterparts (described below), except that the names of the attributes must have a hyphen ('-') prepended to the attribute name (e.g., 'value' becomes '-value'). The following is a list of attributes available to the new method:

-name
-value
-data
-active

Each of these attributes corresponds directly to its similarly-named method.

Examples:

    ## use name and value
    $env = new Config::Crontab::Env( -name  => 'MAILTO',
                                     -value => '[email protected]' );
    ## parse a whole string
    $env = new Config::Crontab::Env( -data => '[email protected]' );
    ## use name and value to create an inactive object
    $env = new Config::Crontab::Env( -active => 0,
                                     -name   => 'MAILTO',
                                     -value  => 'mike', );
    $env->active(1);  ## now activate it
    ## create an object that will unset the environment variable
    $env = new Config::Crontab::Env( -name => 'MAILTO' );
    ## another way
    $env = new Config::Crontab::Env( -data => 'MAILTO=' );
    ## yet another way
    $env = new Config::Crontab::Env;
    $env->name('MAILTO');

If bogus data is passed to the constructor, it will return undef instead of an object reference. If there is a possiblility of poorly formatted data going into the constructor, you should check the object variable for definedness before using it.

If the -data attribute is present in the constructor when other attributes are also present, the -data attribute will override all other attributes.

name([string])

Get or set the object name.

Example:

    $env->name('MAILTO');

value([string])

Get or set the value associated with the name attribute.

Example:

    $env->value('[email protected]');
    print "The value for " . $env->name . " is " . $env->value . "\n";

data([string])

Get or set a raw environment line.

Example:

    $env->data('[email protected]');
    print "This object says: " . $env->data . "\n";

active([boolean])

Get or set whether the Env object is active. In practical terms, this simply inserts a pound sign before the name field when accessing the dump method. It may be used whenever convenient.

    print $env->dump . "\n";

is the same as:

    print ( $env->active ? '' : '#' ) . $env->data . "\n";

dump

Returns a formatted string of the Env object. This method is called implicitly when flushing to disk in Config::Crontab. It is not newline terminated.

    print $env->dump . "\n";

PACKAGE Config::Crontab::Comment

This section describes Config::Crontab::Comment objects (hereafter Comment objects). A Comment object is an abstracted way of dealing with crontab comments and whitespace (blank lines or lines that consist only of whitespace).

METHODS

new([%args])

Creates a new Comment object. You may create Comment objects in any of the following ways:
Empty
    $comment = new Config::Crontab::Comment;
Populated
    $comment = new Config::Crontab::Comment( -data => '# this is a comment' );

and an alternative:

    $comment = new Config::Crontab::Comment( '# this is a constructor shortcut' );

Constructor attributes available in the new method take the same arguments as their method counterparts (described below), except that the names of the attributes must have a hyphen ('-') prepended to the attribute name (e.g., 'data' becomes '-data'). The following is a list of attributes available to the new method:

-data

Each of these attributes corresponds directly to its similarly-named method.

Examples:

    ## using data
    $comment = new Config::Crontab::Comment( -data => '## a nice comment' );
    ## using data method
    $comment = new Config::Crontab::Comment;
    $comment->data('## hi Mom!');

If bogus data is passed to the constructor, it will return undef instead of an object reference. If there is a possiblility of poorly formatted data going into the constructor, you should check the object variable for definedness before using it.

As a shortcut, you may omit the -data label and simply pass the comment itself:

    $comment = new Config::Crontab::Comment('## this space for rent or lease');

data([string])

Get or set a comment.

Example:

    $comment->data('## this is not the comment you are looking for');

dump

Returns a formatted string of the Comment object. This method is called implicitly when flushing to disk in Config::Crontab. It is not newline terminated.

CAVEATS

  • Thanks to alert reader ``Kirk'' (no lastname given), we learn that some versions of Debian linux's ``crontab -l'' does not strip the internal crontab(1) comments (e.g., ``DO NOT EDIT THIS FILE'' and subsequent meta-data) at the start of user crontabs.

    This means that if you use Config::Crontab to edit a user's crontab file, those three headers will be added to the Config::Crontab object, and written back out again, and crontab(1) will add its own comments, effectively adding 3 comment lines each time you edit the crontab.

    You may use this little heuristic as a starting point for stripping those comments:

        my $ct = new Config::Crontab;
        $ct->read;
        
        ## make "crontab -l | crontab -" idempotent for Debian
        for my $line ( grep { defined } ($ct->select(-type => 'comment'))[0..2] ) {
            if( $line->data =~ qr(^# (?:DO NOT EDIT|[\(]\S+ installed|[\(]Cron version)) ) {
                $ct->remove($line);
            }
        }
        
        ...
        
        $ct->write;
    
  • As of version 1.05, Config::Crontab supports the user field (with optional ':group' and '/<login-class>') via the -system initialization parameter, system Event method, or user Event method and Event initialization parameter.
  • You will not get good results adding non-Block objects to a Crontab object directly:

        $ct->last( new Config::Crontab::Event(-data => '1 2 3 4 5 /bin/friday') );
    

    This doesn't do anything (and shouldn't). You should be adding Block objects to the Crontab object instead:

        $block->last(new Config::Crontab::Event(-data => '1 2 3 4 5 /bin/friday'));
        $ct->last($block);
    

    or the slightly more economical:

        $ct->last( new Config::Crontab::Block(-data => '1 2 3 4 5 /bin/friday') );
    

    This is nice since the Block constructor parses its -data parameter as raw data and creates all the necessary objects to populate itself. The downside of this last approach is that you don't get a handle to your block if you need to make later changes. It can be easily got, however, since we appended it to the end (using last) of the Crontab object:

        $block = ($ct->blocks)[-1];
    

TODO

  • a better query language that would allow for boolean operators and more complexity (SQL, maybe? I've seen that in one of Ken William's modules using Parse::RecDescent)
  • would be cool to use some fancier datetime parsers that can guess when an event will occur and allow that in our select methods. I've seen one of those on CPAN but didn't look too closely. Maybe someone will use both if they need both.
  • need copy constructors (and clone method)
  • need to be more strict about strict (it should do more things, enable more regex checks on data, etc.)
  • some pretty-print options for dump
  • alternative crontab syntax support (e.g. SysV-syntax used by Solaris doesn't support weekday 7 or 3-letter month and day name abbreviations)

    Config::Crontab will support SysV-syntax since it is a proper subset of Vixie cron syntax, but you will need to necessarily perform your own syntax checking and omit elements unique to Vixie cron in your UI.

ACKNOWLEDGEMENTS

  • Juan Jose Natera Abreu ([email protected]) for unsafe POSIX::tmpnam alert; now using File::Temp.

AUTHOR

Scott Wiersdorf, <[email protected]>

COPYRIGHT AND LICENSE

Copyright (C) 2007 by Scott Wiersdorf

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.6 or, at your option, any later version of Perl 5 you may have available.