Crontab(3pm)
π
Crontab(3pm) β the Config::Crontab era π
User Contributed Perl Documentation Β· Perl module vibes only Β· bestie, we're about to read AND write crontabs with objects, and it's giving β¨main characterβ¨
β¨ NAME β¨
Config::Crontab β Read/Write Vixie compatible crontab(5) files. That's it, that's the whole vibe π
πΈ SYNOPSIS πΈ
okay so here's the whole tutorial arc in code, no cap:
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;
(notice the last one needs root perms, bestie β we do NOT have root perms, we have β¨hopesβ¨)
π¦ DESCRIPTION π¦
so Config::Crontab is literally an object-oriented interface to Vixie-style crontab(5) files, but for Perl π«Ά
a Config::Crontab object lets you mess with an ordered set of Event, Env, or Comment objects β those are all included with this package, and they each get their own description below. lowkey iconic of them.
in short: Config::Crontab reads and writes crontab(5) files (and does a little pretty-printing too, because aesthetic matters π
) using objects. the general idea is you create a Config::Crontab object and associate it with a file. if it's unassociated, it'll just 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. periodt.
- β’ NOTE:
Config::Crontabdoes not (currently) do validity checks on your data (i.e., dates out of range, etc.). however, if the call tocrontabfails when you invokewrite, thenwritewill returnundefand seterrorwith the error message returned from thecrontabcommand. future development may tend toward more validity checks. so likeβ¦ it's not checking your homework rn π
now, to successfully navigate the module's ins and outs, we're gonna need a little terminology lesson. sit down, drink some water.
π§ Terminology π§
Config::Crontab (hereafter just Crontab, because we're besties like that) 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. yes, even when they're asleep π΄
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. same energy as above π
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:
MAILTO=joe@schmoe.org
## 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 => joe@schmoe.org | | |
| | | -data => MAILTO=joe@schmoe.org | | |
| | +---------------------------------------------+ | |
| +---------------------------------------------------+ |
| |
| +---------------------------------------------------+ |
| | 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 Config::Crontab::Block objects. nesting goals fr fr πͺ
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. iykyk π
π 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. it's giving arts and crafts but for cron βοΈ
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). one job running twice is NOT the vibe π
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::Crontabobject must have itsreadmethod invoked for it to read the crontab file. - β’ the
selectmethod 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 ofselectinto scalar context and we would get the number of items in the list instead of the list itself). classic gotcha π - β’ 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
writemethod.
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"));
three ways to do the same slay, pick your fighter π
...and okay so here's what that example just taught us, bestie, take notes πβ¨:
- Only
Blockobjects can be added toCrontabobjects (peep"CAVEATS"for the tea β).Blockobjects may be added via thelastmethod β and honestly several other methods too, includingfirst,up,down,before, andafter. Blockobjects can be populated a whole bunch of ways π , including the-dataattribute (a string that may β and frequently does β span multiple lines via a 'here' document), the-linesattribute (which takes a list reference), and thelastmethod. And not justlast:Blockobjects use the same methods for adding and moving objects that theCrontabobject does βfirst,last,up,down,before, andafter. iconic behavior, no cap π
After the Module Utility section, the rest of this doc is a straight-up reference manual β it describes every method available (and how to actually use them) across all 5 classes: Config::Crontab, Config::Crontab::Block, Config::Crontab::Event, Config::Crontab::Env, and Config::Crontab::Comment. Also pls pls pls go look at the example CGI script in the eg directory, and the (somewhat contrived, ngl) examples in the t (testing) directory that ships with this distribution π«Ά
Module Utility β¨
Config::Crontab is a useful module by virtue of the "one-liner" test. Like, a useful module has to do useful work (editing crontabs = useful work, fr) economically β meaning the useful work has to be doable on a single command-line that doesn't wrap more than twice and that an adept Perl programmer can actually understand. π§ π
Graham Barr's Net::POP3 module is a great example of a useful module (honestly most of Graham's work falls in this category, king behavior π).
So, 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'joe@schmoe.org':
perl -MConfig::Crontab -e '$c=new Config::Crontab; $c->read; \
$_->value(q!joe@schmoe.org!) 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 is all about Config::Crontab objects (from here on out, just "Crontab objects", bestie, we're close like that π«). A Crontab object is an abstracted way of dealing with an entire crontab(5) file. The Crontab class comes with methods that let you select, add, or remove Block objects, plus read and parse crontab files and write crontab files. it's giving full control, lowkey ποΈβ¨
init([%args]) πΈ
This method gets called implicitly when you instantiate an object via new. init takes the exact 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 whenever you wanna 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, periodt:
- if the file specified by the
filemethod (or-fileattribute innew) does not exist at the timereadis invoked,readsetserrorand dies:"Could not open (filename): (reason)". Ifstrictis disabled,readreturnsundef(erroris set). - If the file specified by the
filemethod (or-fileattribute innew) cannot be written to, or the"crontab"command fails,writesetserrorand warns:"Could not open (filename): (reason)". Ifstrictis disabled,writereturnsundef(erroris set). - Croaks if an illegal username is specified in the
-ownerparameter. π¨
Examples:
## disable strict (default)
$ct->strict(0);
system([boolean]) π₯οΈ
system tells config::crontab to assume that the crontab object follows 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 just get lumped in with the command π classic. When enabled, the user field becomes 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 by using owner before a read or write method gets called:
$c = new Config::Crontab( -owner => 'joe' );
$c->read; ## reading joe's crontab
Or another way, bestie:
$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 about what it'll allow for a username, because this info internally gets passed to a shell. so like, safety first obvs π 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) β however, it 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, then next time this instance parses a crontab file, it'll 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. so handy fr fr π«Ά
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 β go off, stack 'em π. 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, we're chill like that).
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
so like, the value of whatever object method you named gets negatively matched using Perl regular expressions (go peep perlre bestie) instead of boring old string comparison β internally it's the !~ operator doing all the work π
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]) β¨
Hands you back a whole little list of crontab Block objects that match whatever criteria you slid in there π and if you pass no criteria at all, select_blocks just acts exactly like the blocks method does β it gives you every block in the crontab object, no gatekeeping π
Here's the tea on which criteria keys you've got:
-indexβ an integer, or a list reference full of integers. Gives you back the list of blocks indexed by that integer (or those integers) π¦
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] );
Real talk though: select_blocks returns Block objects, which means if you actually wanna get at the data elements inside those blocks, you're gonna have to go through the lines or select method first, bestie:
## 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) πΈ
Gives you the block that this line belongs to π and if that line isn't found in any block at all? You get undef, sorry babes π
Oh and heads up: $line has to be a Config::Crontab::Event, Config::Crontab::Env, or Config::Crontab::Comment object. No substitutes.
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) π
Yeets a block out of the crontab file if you handed it a block, or yeets just a single crontab line out of its block if you handed it a crontab line object. Either way, something's getting removed bestie β¨
Example:
## remove this block from the crontab
$ct->remove($block);
## remove just a line from its block
$ct->remove($line);
π«Ά replace($oldblock, $newblock) π«Ά
Swaps $oldblock out for $newblock β glow-up complete π It returns $oldblock if it worked, and undef if it didn't. No cap.
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 two shuffle a single Config::Crontab::Block object up or down inside the Crontab object's internal array π₯ And if that Block object isn't already a member of the array? It just gets added β first position for up, last position for down. Also go peek at first and last, and the up and down methods over in the Block class, iykyk.
Example:
$ct->up($block); ## move this block up one position
β first(@block), last(@block) β
These move the Config::Crontab::Block object(s) to the first or last positions in the Crontab object's internal array π« and again, if the block isn't already a member of that array, it gets added in the first or last position respectively. So efficient of it.
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 slide the Config::Crontab::Block object(s) to the position immediately before or after the $look_for (or reference) block inside the Crontab object's internal array. Situational placement, we love to see it.
If those objects aren't members of the array yet, they get added before or after the reference block respectively. And if the reference object doesn't even exist in the array? The blocks get moved (or added) to the beginning or end of the array respectively β basically behaving 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 that the file method says to use π But if file isn't set (or is false), write will try to write to a temporary file and then load it up through the crontab program (like, crontab filename).
You can also pass an optional filename as an argument to set file, and that filename gets used from then on π
If write fails, error gets set. Periodt.
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, bye bye π If file is set, that file gets unlinked. If file isn't set (or is false), remove_tab will try 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 gets set. Keep an eye on that.
Example:
$ct->remove_tab(''); ## unset file() and remove the current user's crontab
π error([string]) π
Returns the last error that got encountered (usually during a file I/O operation, sigh). Pass an empty string to reset it β and lowkey calling init resets it too π§
Example:
print "The last error was: " . $ct->error . "\n";
$ct->error('');
π dump π
Returns a string containing the crontab file. That's it, that's the method. Iconic.
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 π
okay bestie, this section is all about Config::Crontab::Block objects (iconic name, and from here on we're just gonna call them Block objects because we're casual like that π
). A Block object is the abstracted lil way this module deals with groups of crontab(5) lines. And how the group gets formed? Depends entirely on how Config::Crontab parsed the file (peep the read and mode methods up in Config::Crontab). So a block can be:
- a single line β like a crontab event, an environment setting, or a comment. just one lonely lil line π₯Ί
- a "paragraph" of lines β a group of lines where each group is separated by at least two newlines. this one is the default parsing mode, no cap.
- the entire crontab file β the whole thing. one block. everything. the whole vibe. π
So the default for Config::Crontab is to read in block (paragraph) mode. Which is honestly the bestie behavior, because it lets you group lines that share a similar purpose, AND order lines within a block β which matters a lot, because (for example) you often want an environment setting to actually take effect before certain cron commands execute. periodt.
an illustration might help here, so let's go:
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 how each block has its own internal line numbering β blocks got their own little ecosystem fr fr π¦. And yes, vertical space was inserted between blocks to make the block structures obvious. Block mode parsing is the default. remember that.
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. every single one. π And you normally don't want to read in line mode unless your crontab file doesn't have paragraph breaks in it β because here's the tea: the dumper prints a newline between each block, so if every line is its own block, you end up with an extra newline between each line. not the look you're going for, bestie.
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 there's only one block in file mode β the whole file, one singular block, main character energy π β and each line is a block line, but not a separate block. subtle but crucial distinction, iykyk. πΈ
β¨ METHODS β¨
ok bestie, this section is every single thing you can do to a Block object. grab a snack, we're going through all of them π
new([%args])
Makes you a brand new Block object π. And you can build one however you like, literally any of these ways:
Empty β zero content, maximum potential:
$event = new Config::Crontab::Block;
Fully Populated β just hand it the goods on day one:
$event = new Config::Crontab::Block( -data => <<_BLOCK_ );
## a comment
5 19 * * Mon /bin/fhe --turn=dad
_BLOCK_
The constructor attributes you get in new take the same arguments as their method counterparts (those are described below, don't worry, we get there), except the attribute names need a hyphen (-) slapped on the front (lines becomes -lines, iconic little formatting rule π
). Here's the full list of attributes available to new:
datalines
If the -data attribute is hanging out in the constructor and other attributes are there too, then -data overrides all the others. no cap. π
Each one 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
MAILTO=sysadmin@mydomain.ext
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
MAILTO=sysadmin@mydomain.ext
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 you feed the constructor bogus data, it will hand you back undef instead of an object reference π. So if there's any possibility of poorly formatted data going into the constructor, check your object variable for definedness before you use it. fr fr, do the check.
And yeah, saying it again because it matters: 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. Under the hood, Block hands its arguments off to other objects to parse whenever a parameter is present. lowkey magic β¨
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 your block data as a list of Config::Crontab::* objects. Set block data by passing a list reference. That's the whole vibe.
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 criteria you specify. And yes you can stack multiple criteria, go off π
Field names should be preceded by a hyphen (though no-hyphen is acceptable too β we use hyphens to dodge the need for quoting keys and to avoid potential bareword collisions).
If you don't pass any criteria at all, select just returns a list of every line in the block (basically the lines behaviour).
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)
Yeets Config::Crontab::* objects out of this block. bye bestie π
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)
Swaps $oldobj out for $newobj inside a block. Returns $oldobj if it worked, undef if it didn't. glow-up complete β¨
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 move the Config::Crontab::* object up or down within the block. shuffle time π¦
If the object isn't a member of the block, it gets added to the block β first position for up, 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 move the Config::Crontab::* object(s) to the first or last positions in the block. main character energy for whichever object you pick π
If the object or objects aren't members of the block, they get 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 move the Config::Crontab::* object(s) to the spot immediately before or after the $look_for (or reference) object in the block. positioning is everything π
If the objects aren't members of the block, they get added to the block before or after the reference object. And if the reference object doesn't exist in the block at all, the objects get 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 you give it no arguments, active returns true but does absolutely nothing (iconic of it). Otherwise, the boolean you used to activate or deactivate the block is what gets returned.
Got a whole series of related crontab lines you want to comment out (or uncomment)? This is the handy shortcut for exactly that, bestie. One thing though: you cannot deactivate Comment objects β they will always be comments, that's just who they are π
Example:
$block->active(0); ## deactivate this block
nolog(boolean)
This one is (currently) a SuSE-specific extension. Straight 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 adds or removes that hyphen for a given cron event line (regardless of whether the user is root or not). shhh π€«
Example:
$block->nolog(1); ## quiet all entries in this block
flag(string)
Flags a block, or an object inside a block, with whatever data you specify. The data is completely up to you β you're the artist π. This is super handy if you need to operate on a bunch of objects at once and don't wanna risk pulling the rug out from under some of them (i.e., deleting numbered elements from a list changes the numbering of the subsequent objects in that 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 (and it recursively calls all its objects' dump methods too, so it's the whole family portrait πΈ). A Block dump is newline terminated.
Example:
print $block->dump;
π PACKAGE Config::Crontab::Event π
ok this section is all about Config::Crontab::Event objects (from here on out we're just calling them Event objects, we're close like that π). An 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 β because in Event object terms, an event that's been commented out is inactive, and events that haven't been commented out are active. the more you know β
π¦ Terminology π¦
Here's your little terminology guide for this class, bestie:
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 the subsequent sections.
β¨ METHODS β¨
This section is all about the methods available to manipulate Event objects' creation and attributes. let's get into it π
π new([%args]) π
Makes u a brand new Event object, bestie. And like, there are so many ways to make one, pick ur fighter:
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, );
The constructor attributes u can pass to new take the exact same arguments as their method counterparts (those r described down below β¬οΈ), except β and this is the lil gotcha β the attribute names need a hyphen (-) stuck on the front (so like, month becomes -month). Here's the full roster of attributes new will accept:
-minute-hour-dom-month-dow-special-data-datetime-user-system-command-active
Every single one of these maps directly onto the method that shares its name. periodt. π
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
β οΈ ok so if u feed the constructor some bogus data, it does NOT hand u back an object reference β it returns undef instead. so if there's any chance ur data might be poorly formatted going in, pls pls pls check ur object variable for definedness before u go using it. don't get played. π
π°οΈ a note about the datetime fields π°οΈ
Event objects have several ways of setting the datetime fields, and honestly? iconic flexibility:
## 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. And here's the tea β β if u set datetime using a special field, or if u initialize an Event object using a special datetime field, the standard datetime fields get reset to '*' and become invalid.
The special datetime field is one single field that stands in for all 5 of the standard datetime fields (go check crontab(5) and "special" for the receipts). Currently, if u set special via the special method, the standard datetime fields (like minute, hour, etc.) are not reset; but the standard datetime fields are reset to '*' if u set special via the datetime method. yes, it's giving inconsistent, i know. π
See the other important info in the datetime and special method descriptions below.
π Also: if the-dataattribute is present in the constructor while other attributes are ALSO present,-dataoverrides all of them. every time. no discussion.
β° minute([digits]) β°
Get or set the minute attribute of the Event object. slay.
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 straight from crontab(5), bestie:
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 can be a digit (1-12) or a three character English abbreviated month string (Jan, Feb, etc.). pick ur vibe.
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 up there β¬οΈ
β¨ special([string]) β¨
Get or set the special datetime field.
The special datetime field is one of these (straight from crontab(5)):
@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 u set a datetime via special, it will override anything sitting in the other standard datetime fields. no cap.
And listen β u may use a special datetime string as an argument to the datetime method, but u may NOT use a standard datetime string in the special method. Currently there's no error checking on this field, so the object won't yell at u... but the behavior is undefined. tread carefully bestie. π
The datetime method will return the special value in preference to any other standard datetime fields. Like, if special has a value (e.g., '@reboot', etc.) it'll be the thing returned in all methods that return aggregate event data (e.g., datetime, dump, data, etc.). If special is false, then the standard datetime fields get returned instead. So basically u should always check the value of special before touching any of the standard datetime fields:
if( $event->special ) {
print $event->special . "\n";
}
## use standard datetime elements
else {
print $event->minute . " " . $event->hour ...
}
But if ur presenting the whole datetime field all formatted and pretty, just use the datetime method and u don't have to do any checks on special at all:
## 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 literally 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. teamwork honestly. π«Ά
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.
The 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 super convenient shortcut for parsing a datetime field when ur not precisely sure what's inside it (but u ARE sure it's either a special datetime field or a standard datetime field):
$event->datetime($some_string);
While u may pass a special datetime field into datetime, u may not pass a standard field into the special method. Currently the object won't complain, and it may even work in most cases, but the behavior is undefined and will likely get more strict in the future. so like, don't build ur whole thing on it. π
π€ user([string]) π€
Get or set the user part of a system event object.
Example:
$event->user('joeuser');
π‘ Theuserfield is only accessible when the crontab object was created or parsed with system mode enabled (see"system"above).
βοΈ system([boolean]) βοΈ
When set, this will parse a -data string looking for a username sitting before the command, exactly 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'. Real talk tho β if you hand the Event parser garbage, it genuinely cannot save you, because as of version 1.05 the user syntax (including that whole '/<login-class>' situation) is supported:
$event = new Config::Crontab::Event( -data => '2 5 * * * /bin/foo --args',
-system => 1 );
The Event object is gonna end up with '/bin/foo' as its user and '--args' as its command. Which is lowkey fine when you write it back out to a file β but bestie, if you try to grok the command field you are not getting what you're expecting. π Not even close.
β¨ command([string]) β¨
Gets or sets the command part of an Event object. That's it, that's the whole job. π
Example:
$event->command('/bin/foo with args here');
β¨ active([boolean]) β¨
Gets or sets whether the Event object is active. Practically speaking? It just shoves a pound sign in front of the datetime fields when you hit the dump method. dump uses it implicitly, but you can absolutely poke at it separately whenever it's convenient for you. π
print ( $event->active ? '' : '#' ) . $event->data . "\n";
is literally the same thing as:
print $event->dump . "\n";
β¨ dump β¨
Returns a formatted string of the Event object. Config::Crontab calls this implicitly when it flushes to disk. Heads up: it is not newline terminated, so you gotta add your own "\n" like the icon you are. π
Example:
print $event->dump . "\n";
π¦ PACKAGE Config::Crontab::Env π¦
Okay so this section is all about Config::Crontab::Env objects (from here on out: Env objects, we're on a first-name basis). An Env object is the abstracted, glamorous way of dealing with crontab lines that look like this (peep crontab(5) for the receipts):
name = value
Straight from crontab(5), and I'm quoting here:
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.
Just like Event objects, Env objects can be active or inactive β the whole difference is that an inactive Env object is commented out, like:
#FOO=bar
πΈ Terminology πΈ
Given the following crontab environment line:
MAILTO=joe
we have officially defined these parts of the Env object:
MAILTO = joe
====== ============ =====
name (not stored) value
(Yes, the = itself is not stored. It's just vibes. π«Ά)
These methods and the other methods for accessing and manipulating Event objects get described in the upcoming sections.
π METHODS π
β new([%args]) β
Creates a new Env object. You can build an Env object in literally any of these 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' );
The constructor attributes you can pass to new take the exact same arguments as their method counterparts (described down below) β the only little catch is that attribute names need a hyphen ('-') glued to the front (so 'value' becomes '-value'). Here's the full roster of attributes available to new:
-name-value-data-active
Each one of these corresponds directly to its similarly-named method. Symmetry, we love to see it. β¨
Examples:
## use name and value
$env = new Config::Crontab::Env( -name => 'MAILTO',
-value => 'joe@schmoe.org' );
## parse a whole string
$env = new Config::Crontab::Env( -data => 'MAILTO=joe@schmoe.org' );
## 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 you pass bogus data to the constructor, it does not throw hands β it returns undef instead of an object reference. So if there's any chance of poorly formatted data sliding into your constructor, check that variable for definedness before you use it. Fr fr. π
π And if-datashows up in the constructor alongside other attributes,-datawins. It overrides every single other attribute. No discussion.
β name([string]) β
Get or set the object name.
Example:
$env->name('MAILTO');
β value([string]) β
Get or set the value that's associated with the name attribute. The duo. The ship. π«Ά
Example:
$env->value('tom@tomorrow.org');
print "The value for " . $env->name . " is " . $env->value . "\n";
β data([string]) β
Get or set a raw environment line. Raw. Unfiltered. Iconic.
Example:
$env->data('MAILTO=foo@bar.org');
print "This object says: " . $env->data . "\n";
β active([boolean]) β
Get or set whether the Env object is active. Practically? It just drops a pound sign before the name field when you access the dump method. Use it whenever it's convenient, bestie.
print $env->dump . "\n";
is the exact same as:
print ( $env->active ? '' : '#' ) . $env->data . "\n";
β dump β
Returns a formatted string of the Env object. Config::Crontab calls this implicitly when it flushes to disk. Not newline terminated, so don't forget that "\n" yourself. π
print $env->dump . "\n";
π PACKAGE Config::Crontab::Comment π
This section is about Config::Crontab::Comment objects (aka Comment objects, we're cozy). A Comment object is the abstracted way of dealing with crontab comments and whitespace β and yes, that means blank lines and lines that are literally nothing but whitespace. They all count. π
π¦ METHODS π¦
πΈ new([%args]) πΈ
Creates a new Comment object. You may create Comment objects in any of these 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' );
The constructor attributes available to new take the same arguments as their method counterparts (described below) β except, same as always, the attribute names need a hyphen ('-') prepended to them (so 'data' becomes '-data'). Here's the list of attributes available to new:
-data
Each one 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!');
β οΈ Same energy as before: if you pass bogus data to the constructor, it returns undef instead of an object reference. So if there's a possiblility of poorly formatted data going into the constructor, you really should check the object variable for definedness before using it. π
As a shortcut, you can totally skip the -data label and just 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. Config::Crontab calls this implicitly when flushing to disk. And you already know β it is not newline terminated. π«Ά
π₯ CAVEATS π₯
- Thanks to alert reader "Kirk" (no lastname given, mysterious king π), we learn that some versions of Debian linux's
"crontab -l"do not strip the internalcrontab(1)comments (things like"DO NOT EDIT THIS FILE"and the meta-data that follows) from the start of user crontabs.
Which means: if you use Config::Crontab to edit a user's crontab file, those three headers get added to the Config::Crontab object, then written back out again, and then crontab(1) adds its own comments β effectively stacking 3 comment lines on every single edit. Every time. It compounds. π
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::Crontabsupports the user field (with the optional':group'and'/<login-class>') via the-systeminitialization parameter, thesystemEvent method, or theuserEvent method and its Event initialization parameter. β¨ - Bestie, you will not get good results adding non-Block objects directly to a Crontab object:
$ct->last( new Config::Crontab::Event(-data => '1 2 3 4 5 /bin/friday') );
This doesn't do anything (and honestly it shouldn't). What you want to be doing is 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 because the Block constructor parses its -data parameter as raw data and creates every single object it needs to populate itself. πΈ The downside of that last approach? You don't get a handle on your block if you need to make later changes. But it's honestly easy to grab back, since we appended it to the end (using last) of the Crontab object:
$block = ($ct->blocks)[-1];
π TODO π
okay so here's the wishlist, the "one day bestie" list, the things that are not done yet but that the author is manifesting β¨:
- 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
selectmethods. 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 a
clonemethod) 𧬠- 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
7or 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. (like, no shortcuts bestie, that part is on you π
)
π«Ά ACKNOWLEDGEMENTS π«Ά
- Juan Jose Natera Abreu (
naterajj@yahoo.com) for the unsafePOSIX::tmpnamalert; now usingFile::Temp. (we love a security glow-up π)
π SEE ALSO π
like, go read the classics, they're the blueprint fr fr πβ¨
π AUTHOR π
Scott Wiersdorf, <scott@perlcode.org> π
π 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. π
and that's a wrap bestie!! π the whole thing is slayed π
this page is from perl v5.36.0 and it's dated 2022-10-22, filed under Crontab(3pm) β go forth and schedule your little heart out, no cap π¦β¨
π¦ where this page comes from
- ubuntu noble: libconfig-crontab-perl 1.45-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libconfig-crontab-perl 1.45-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms