For a project I’ve been working on, I needed to be able to schedule notifications to occur in a highly customized manner and rather than write something insane from scratch, I decided to leverage cron.
This PHP Class is fairly dependent on your environment. It probably won’t work if safe mode is enabled; it won’t work if the user apache runs as is in the cron.deny file; it surely won’t work on anything but a *nix machine. I’ve only tested it on a CentOS machine and while it should work on just about any linux machine with a relatively up-to-date version of PHP5, I can’t promise anything.
With that out of the way, you can download the source at http://greenservr.com/projects/crontab/crontab.phps
This example adds a task that runs every hour, from the 20 to the 30 of the hour, every hour of every day and month. Then, it adds a job that runs from the 35-40.
$crontab = new Crontab(); $crontab->on('* * * * *'); $crontab->onMinute('20-30')->doJob("echo foo;"); $crontab->onMinute('35-40')->doJob("echo bar;"); $crontab->activate();
Something to note about the above example, specifically the “on()” method. This lets you directly define the time portion of the crontab entry. Please note that this method does not do any checking on how many items you have. In the case above, I used it to default all the time elements to the wild-card character.
The first example appended the two new jobs onto whatever is currently in the crontab for the user. If you would rather remove all existing jobs and add only your new ones. A parameter of
false instructs the activate method to not include any existing cron jobs.
$crontab = new Crontab(); $crontab->on('* * * * *'); $crontab->onMinute('20-30')->doJob("echo foo;"); $crontab->onMinute('35-40')->doJob("echo bar;"); $crontab->activate(false);
Lastly, if you want to read what is currently in the crontab for the user, just use the
I really encourage you to take a look at the class to see all of its methods and variables. They are fairly well documented and straightforward.
If you end up using this in a project of yours, I’d really enjoy hearing about it.