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.
<?php

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
<?php

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值