PHP and Cron

PHP and Cron

Usually, it makes sense to run the cron job in crontab and trigger a PHP script command.

But I have a single IOCUtil object and a lot of related codes there. So on top of a cron parser, I provide a CronService.php class as follow:

"mtdowling/cron-expression": "^1.1"

The method run will be called several times.

namespace BillingConsumerPHP;

require __DIR__.'/../../vendor/autoload.php';

use \Cron\CronExpression;
use \DateTime;

class CronService
{

private $ioc = null;

private $crons = null;

private $jobs = null;

public function __construct($ioc)
{
$this->ioc = $ioc;
}

public function addJob($jobName, $jobPattern){
$cron = CronExpression::factory($jobPattern);
$this->crons[$jobName] = $cron;

$this->jobs[$jobName] = null;
}

public function run(){
$now = new DateTime("now");
foreach ($this->jobs as $key => $value){
if(null !== $value && !empty($value)){
//have cache, compare
$next = $value;
if($now >= $next){
//execute
$this->call($key);

//calcuate next one to cache
$cron = $this->crons[$key];
$next = $cron->getNextRunDate();
$this->jobs[$key] = $next;
}
}else{
//calculate the next date
$cron = $this->crons[$key];
$next = $cron->getNextRunDate();
if($now >= $next){
//excute
$this->call($key);

//calcuate next one to cache
$next = $cron->getNextRunDate();
$this->jobs[$key] = $next;
}else{
$this->jobs[$key] = $next;
}
}
}
}

private function call($jobName){
$logger = $this->ioc->getService("logger");

switch ($jobName) {
case 'backupData':
$this->backupData();
break;
default:
$logger->warning("jobName {$jobName} is not defined in system!");
}
}

public function backupData(){
$logger = $this->ioc->getService("logger");

$logger->debug("try to backup data to mysql");
}

}

?>

Every time it will check the next run time with current time to decide if we should run some tasks. There is short comings, if one task takes too long time, system will miss some tasks in schedule.

Unite tests

use \BillingConsumerPHP\IOCUtil;

/**
*
* RUNNING_ENV=test phpunit --bootstrap vendor/autoload.php tests/BillingConsumerPHP/CronServiceTest
*
* @author carl
*
*/
class CronServiceTest extends PHPUnit_Framework_TestCase
{

private $cronService;

protected function setUp()
{
$ioc = new IOCUtil();
$this->cronService = $ioc->getService("cronService");

}

public function testDummy()
{
$this->assertTrue(true);

}


public function testCronService(){
$this->cronService->addJob('backupData', '* * * * * *');


$i = 0;

while($i<10){

$this->cronService->run();


$i++;


}

}

}

?>

Reference:
https://github.com/mtdowling/cron-expression

你可能感兴趣的:(PHP)