`
sillycat
  • 浏览: 2539345 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

PHP and Cron

    博客分类:
  • PHP
 
阅读更多
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
分享到:
评论

相关推荐

    《Better PHP Development》- 2017 英文原版

    With PHP 7+ came some improvements that make it harder to make mistakes, and 7.2 is making things even safer, even more structured. If you’re just getting started with the language (or perhaps youve ...

    无标题php搭建网站源码

    2. **ajax.php**: AJAX(Asynchronous JavaScript and XML)是一种创建动态网页的技术,它允许页面在不重新加载整个页面的情况下与服务器交换数据并更新部分网页内容。这个文件可能包含处理异步请求的PHP代码,例如...

    一个PHP一直执行的例子 不会计划任务可以用这个 PHP+jquery前台动态显示数据库内容

    jQuery在前端的角色是负责发送AJAX(Asynchronous JavaScript and XML)请求到服务器,获取PHP脚本返回的最新数据。AJAX允许在不重新加载整个网页的情况下,与服务器交换数据并局部更新页面。在这个场景下,可能使用...

    php.ini-development

    PHP attempts to find and load this configuration from a number of locations. ; The following is a summary of its search order: ; 1. SAPI module specific location. ; 2. The PHPRC environment variable....

    drupal 6.12

    (http://www.php.net/) and either MySQL (http://www.mysql.com/) or PostgreSQL (http://www.postgresql.org/). The Apache web server and MySQL database are recommended; other web server and database ...

    Magento商城_目录结构说明

    - `pear`:PEAR(PHP Extension and Application Repository)安装文件,用于扩展PHP功能。 - `php.ini.sample`:PHP配置文件的示例。 - `STATUS.txt`:显示当前Magento版本的状态。 - `.project`:Eclipse或...

    laravel-docker-cron:laravel Docker的计划工

    Laravel docker cron如何使用git clone https://github.com/yupmin/laravel-docker-croncd laravel-docker-cronlaravel new 安装时间表清单composer require hmazter/laravel-schedule-list例子php artisan make:...

    firmament-master.zip

    在Web开发中,AJAX(Asynchronous JavaScript and XML)常用于实现页面的异步更新,无需刷新整个页面即可与服务器交换数据。这个文件可能包含了处理用户交互、数据提交或后台任务的代码。 3. **index.php**:这是...

    冷迪电影全自动采集程序php版 v2.2

    6. **自动化任务调度**:为了让采集程序定时运行,可能会使用Cron Job或者PHP的cron函数来设置计划任务,定期执行数据采集。 7. **错误处理与日志记录**:在程序中,良好的错误处理和日志记录是必不可少的,可以...

    PHP短网址生成

    5. **cron.php**:Cron是Linux系统下的定时任务工具,cron.php可能是用来设置定期任务的脚本,例如检查过期的短网址或者执行其他维护操作。 6. **config.php**:配置文件,通常存储数据库连接信息、应用设置等关键...

    Ubuntu-使用crontab定时任务

    # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # 分 时 日...

    simple-tags

    * Fix a bug with PHP 4.4 and plugin activation. (PHP4 suck...) * Remove base class for compatibility PHP4. * Fix sanitized HTML on admin. * Fix random order for tag cloud. * Try a fix for support...

    彩虹DS免授权版本独家防红策略.zip

    1. **ajax.php**: 这个文件通常用于处理异步请求,即AJAX(Asynchronous JavaScript and XML)请求。在彩虹DS系统中,它可能被用来处理用户界面与服务器之间的无刷新交互,如数据的动态加载或验证用户输入,同时防止...

    laravel-react:Laravel 8和React 17样板

    php artisan cron:refresh-database npm install && npm run dev php artisan key:gen php artisan serve 选项2 先决条件 确保在计算机上安装了和 。 git clone create a .env file copy content from .env....

    Linux-and-Security-snippets:Linux 和安全脚本和注释

    rsync 示例Linux 测试 cron Linux renice 多个同名进程PHP 使用 Amazon AWS SES 发送邮件,无需额外库删除文件夹中超过天数的文件MySQL 主从复制从 SSL 证书创建 Java KeyStore 用于测试/监视使用身份验证的 Django...

    arth_ansible_task15

    7. **自动化维护任务**:定期更新PHP版本、清理旧版本、检查错误日志等维护任务都可以通过Ansible的定时任务模块`cron`实现。 8. **监控和日志管理**:通过`file`模块收集PHP服务的日志,`syslog`模块可以将日志...

    ImpREC 1.7c

    http://www.tuts4you.com/forum/index.php?showtopic=6410 Thank you! v1.7c FINAL (PUBLIC VERSION) ---------------------------- - Misc - Fixed bug introduced in 1.7b when DLL's have discardable ...

    postfix邮件系统[整理].pdf

    Simple Authentication and Security Layer (SASL) 提供了多种认证机制,Authlib是与SASL一起使用的验证库,用于Postfix的SMTP验证。 11. **sudo授权**: sudo工具允许非root用户执行特定命令,如管理邮件系统,...

Global site tag (gtag.js) - Google Analytics