And I know some people don't, or some people can create a limited number of cron jobs when they need more. So I made this "fake cron" class.. maybe it might work. I haven't tested it, but theoretically in my head it should work. I have doubts about the usage of include(). You guys can tell me what you think. =]
fakecron.class.php
Code: Select all
<?php
class fakeCron
{
/*
** Container for cronjobs stored in the format [time] => script
*/
private $_cronJobs = array();
/*
** The amount of time to wait before checking if a script needs to be run
*/
private $_timeout = 60;
/*
** Method to set the number of seconds between checking if the script needs
** to run.
** @param int $time (in seconds)
** @access public
*/
public function setTimeout($time)
{
$this->_timeout = $time;
}
/*
** Method to add a script and time to run to the cronJobs array.
** @param string $script (script to be executed)
** @param mixed $timeToRun (any time format that can be converted to a timestamp
** using strtotime())
** @access public
*/
public function addCron($script, $timeToRun)
{
if (is_array($timeToRun)) {
foreach ($timeToRun AS $timeEach)
{
$this->_addCron($script, $timeEach);
}
} else
{
$this->_addCron($script, $timeToRun);
}
}
/*
** Internal method to add to $this->_cronJobs array
** @access private
*/
private function _addCron($script, $timeToRun)
{
if (strtotime($timeToRun) !== false) {
$this->_cronJobs[strtotime($timeToRun)] = $script;
} else {
trigger_error('FakeCron: Could not parse time (' . $timeToRun . ') given for script ('
. $script . ') into timestamp', E_USER_ERROR);
}
}
/*
** This method sets the script so it will run hypothetically forever and
** starts an infinite loop, checking if any scripts need to be run and then
** sleep()ing.
** @access public
*/
public function run()
{
ignore_user_abort(true);
set_time_limit(0);
while (true)
{
foreach ($this->_cronJobs AS $k => $v)
{
if (($k <= time()) && ($k >= time()-$this->_timeout)) {
include $v;
}
}
$this->checkKill();
sleep($this->_timeout);
}
}
/*
** Method to check for existence of kill.txt
** If found, the script will exit.
*/
private function _checkKill()
{
if (file_exists('kill.txt')) {
if (!unlink('kill.txt')) {
die('Fake Cron: kill.txt was found and could not be deleted. Fake Cron '
. 'was successfully killed, but will not be able to run in the future. Change '
. 'permissions on kill.txt or manually delete it.');
}
exit;
}
}
}Code: Select all
$fakeCron = new fakeCron();
$fakeCron->addCron('updatestats.php', '12:30 AM'); //runs at 12:30 AM every day
$fakeCron->addCron('sendmailinglist.php', '1 PM'); //runs at 1 PM every day
//runs on specific time on specific date
$fakeCron->addCron('somecron.php', 'Saturday Aug 26, 2007 3:15 AM');
//runs on each time of array of times every day
$fakeCron->addCron('updatestatsagain.php', array('1 PM', '2 PM', '3 PM', '1 AM', '2 AM', '3 AM'));
$fakeCron->run();