定时器

        在平常的项目中我们总是会遇到需要将某个方法任务定时执行的问题,定时执行方法任务如果我们拥有服务器的权限,我们可以直接在服务器设置定时任务,例如在Windows的任务计划程序中进行设置,在Linux中编写脚本进行执行。如果我们没有服务器权限,我们该如何使用项目的程序代码来自动定时执行呢?接下来就为大家描述一个基于ThinkPHP框架定时执行任务的例子,具体的方法会在下面进行详细的描述。

        关于定时执行任务在这里需要提醒的是, 这里描述的方法是被动执行的,也就是说当系统网站产生访问的时候,程序会对比是否达到定时的要求或者说是否达到执行任务的时间来决定是否执行方法任务,如果达到则执行,否则不执行。另外,如果网站没有任何访问和请求则也是同样不执行,如果大家有发现或者知道了如何主动执行定时任务,烦请留言告知,我也学习一下。

1、方法一:v3.2.1

①、ThinkPHP/Library/Behavior/CronRunBehavior.class.php文件

        在这里首先要说的就是这个自动执行任务文件,官方所给的这个文件存在BUG,我是用的是v3.2.1版本,后面的版本是否有改正大家可以尝试一下。

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. /** 
  3.  * ======================================= 
  4.  * Created by WeiBang Technology. 
  5.  * Author: ZhiHua_W 
  6.  * Date: 2016/9/22 0005 
  7.  * Time: 上午 11:12 
  8.  * Project: ThinkPHP实现定时执行任务 
  9.  * Power: 自动执行任务 
  10.  * ======================================= 
  11.  */  
  12. namespace Behavior;  
  13.   
  14. class CronRunBehavior  
  15. {  
  16.     public function run(&$params)  
  17.     {  
  18.         if (C('CRON_CONFIG_ON')) {  
  19.             $this->checkTime();  
  20.         }  
  21.     }  
  22.   
  23.     private function checkTime()  
  24.     {  
  25.         if (F('CRON_CONFIG')) {  
  26.             $crons = F('CRON_CONFIG');  
  27.         } else if (C('CRON_CONFIG')) {  
  28.             $crons = C('CRON_CONFIG');  
  29.         }  
  30.   
  31.         if (!empty($crons) && is_array($crons)) {  
  32.             $update = false;  
  33.             $log = array();  
  34.             foreach ($crons as $key => $cron) {  
  35.                 if (empty($cron[2]) || $_SERVER['REQUEST_TIME'] > $cron[2]) {  
  36.                     G('cronStart');  
  37.                     R($cron[0]);  
  38.                     G('cronEnd');  
  39.                     $_useTime = G('cronStart', 'cronEnd', 6);  
  40.                     $cron[2] = $_SERVER['REQUEST_TIME'] + $cron[1];  
  41.                     $crons[$key] = $cron;  
  42.                     $log[] = 'Cron:' . $key . ' Runat ' . date('Y-m-d H:i:s') . ' Use ' . $_useTime . ' s ' . " ";  
  43.                     $update = true;  
  44.                 }  
  45.             }  
  46.             if ($update) {  
  47.                 ThinkLog::write(implode('', $log));  
  48.                 F('CRON_CONFIG', $crons);  
  49.             }  
  50.         }  
  51.     }  
  52. }  
        此段代码已经将bug修复,大家可以将其复制到 “ ThinkPHP/Library/Behavior/CronRunBehavior.class.php ” 文件中进行保存。

②、tgs.php

        在Application/Common/Conf文件夹中新建tags.php文件,进行标签设置。

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3. return array(  
  4.     //'配置项'=>'配置值'  
  5.     'app_begin' =>array('BehaviorCronRunBehavior'),  
  6. );  

③、config.php

        在Application/Common/Conf文件夹中的config.php文件进行自动运行配置。

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. return array(  
  3.     /* 自动运行配置 */   
  4.     'CRON_CONFIG_ON' => true, // 是否开启自动运行   
  5.     'CRON_CONFIG' => array(   
  6.         '测试执行定时任务' => array('Home/Index/crons', '5', ''), //路径(格式同R)、间隔秒(0为一直运行)、指定一个开始时间   
  7.     ),  
  8. );  

④、IndexController.class.php

        在Application/Home/Controller/IndexController.class.php文件中进行定时执行任务的编写。

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. /** 
  3.  * ======================================= 
  4.  * Created by WeiBang Technology. 
  5.  * Author: ZhiHua_W 
  6.  * Date: 2016/9/22 0005 
  7.  * Time: 上午 11:20 
  8.  * Project: ThinkPHP实现定时执行任务 
  9.  * Power: 自动执行任务方法控制器 
  10.  * ======================================= 
  11.  */  
  12. namespace HomeController;  
  13.   
  14. use ThinkController;  
  15.   
  16. class IndexController extends Controller  
  17. {  
  18.     /* 
  19.     public function index(){ 
  20.     $this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>ThinkPHP</b>!</p></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>','utf-8'); 
  21.     } 
  22.     */  
  23.     public function index()  
  24.     {  
  25.         $contents = file_get_contents("test.txt");  
  26.         //每次访问此路径将内容输出,查看内容的差别  
  27.         var_dump($contents);  
  28.         exit;  
  29.         $this->assign("contents", $contents);  
  30.         $this->display();  
  31.     }  
  32.   
  33.     //定时执行的方法  
  34.     public function crons()  
  35.     {  
  36.         //在文件中写入内容  
  37.         file_put_contents("test.txt", date("Y-m-d H:i:s") . "执行定时任务!" . " <br>", FILE_APPEND);  
  38.     }  
  39. }  

         这样定时执行任务我们就写好了,每隔5秒我们访问任何项目的url,然后查看根目录下的test.txt文件就会发现里面的内容变化。

         注意:当你修改间隔时间时会发现没有生效,这是你需要将Runtime/Data文件夹下的缓存文件删除,间隔时间缓存存放在CRON_CONFIG.php文件中。

         纯净的项目文件下载地址:http://download.csdn.net/detail/zhihua_w/9637267 欢迎大家下载指正。

2、方法2:v3.2.2

        此方法和方法一没有多大的区别。

①、tags.php

        在/Application/Common/Conf目录下新建tags.php文件。(此和方法一处一样)

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3. return array(  
  4.     //'配置项'=>'配置值'  
  5.     'app_begin' =>array('BehaviorCronRunBehavior'),  
  6. );  

②、crons.php

       在/Application/Common/Conf目录下新建crons.php文件。(此处和方法一有区别,注意区分。)

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3. return array(  
  4.     //myplan为我们计划定时执行的方法文件,2是间隔时间,nextruntime下次执行时间  
  5.     //此文件位于/Application/Cron/目录下  
  6.     'cron' => array('myplan', 2, nextruntime),  
  7. );  

③、myplan.php

        在/Application/Common/目录下新建 Cron文件夹,里面新建文件myplan.php文件。

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3. echo date("Y-m-d H:i:s")."执行定时任务!" . " <br>";  

        此时我们就可以访问项目的url,然后我们会发现在Application/Runtime/目录下生成了~crons.php文件,文件内容如下:

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2.   
  3.     return array (  
  4.         'cron' =>  
  5.             array (  
  6.                 0 => 'myplan',  
  7.                 1 => 60,  
  8.                 2 => 1398160322,  
  9.             ),  
  10.     );  
  11.   
  12. ?>  
原文地址:https://www.cnblogs.com/li1056822533/p/7339514.html