Thinkphp5 主动式 计划任务 支持windows和linux

百度搜索过相关的php计划任务的资料,特别是搜索thinkphp的计划任务,目前能明确实现的都是被动式的,就是通过tp3.2自带的计划任务类实现,通过挂钩子的形式,用户访问网站的时候就执行计划任务,这种不是我们需要,我们需要的是全自动,而且配置方便的。在GitHub上搜索的php计划任务有点脱离的tp5框架,如果用的话,需要加载tp5的底层类才行。

我实现的方法就是利用tp5命令行的功能,它能加载底层而且可以让框架在命令行上运行,这样最后部署的时候都可以很容易适应windows和linux,另外一个就是引用了linux的crontab思想,我把配置都放到同一个项目文件下面,这样就不需要为每一个计划任务去设置系统计划配置了。

第一步:设置计划任务的配置
在applicationconfig.php下面添加这个配置,熟悉crontab的朋友就觉得这个格式是不是很像。

/*每分钟*/
/*每小时 某分*/
/*每天 某时:某分*/
/*每周-某天 某时:某分 0=周日*/
/*每月-某天 某时:某分*/
/*某月-某日 某时-某分*/
/*某年-某月-某日 某时-某分*/
'sys_crond_timer' => array('*', '*:i', 'H:i', '@-w H:i', '*-d H:i', 'm-d H:i


第二步:计划任务的核心代码。这一步已经帮大家实现了,大家需要理解的就是tp5的命令行实现就可以。在applicationcommonlib下面创建Crond.php文件。复制下面代码

<?php
namespace appcommonlib; use thinkConfig; use thinkconsoleCommand; use thinkconsoleInput; use thinkconsoleOutput; class Crond extends Command { protected function configure() { $this->setName('Cron') ->setDescription('计划任务'); } protected function execute(Input $input, Output $output) { $this->doCron(); $output->writeln("已经执行计划任务"); } public function doCron() { // 记录开始运行的时间 $GLOBALS['_beginTime'] = microtime(TRUE); /* 永不超时 */ ini_set('max_execution_time', 0); $time = time(); $exe_method = []; $crond_list = Config::get('crond'); //获取第四步的文件配置,根据自己版本调整一下 $sys_crond_timer = Config::get('sys_crond_timer'); foreach ( $sys_crond_timer as $format ) { $key = date($format, ceil($time)); if ( is_array(@$crond_list[$key]) ) { $exe_method = array_merge($exe_method, $crond_list[$key]); } } if (!empty($exe_method)) { foreach ($exe_method as $method) { if(!is_callable($method)) { //方法不存在的话就跳过不执行 continue; } echo "执行crond --- {$method}() "; $runtime_start = microtime(true); call_user_func($method); $runtime = microtime(true) - $runtime_start; echo "{$method}(), 执行时间: {$runtime} "; } $time_total = microtime(true) - $GLOBALS['_beginTime']; echo "total:{$time_total} "; } } }

第三步:配置命令行
在applicationcommand.php 添加一行。注意这个命名空间,包括上面的文件也是。如果你部署的文件夹和我不一样,需要调整一下。

'appcommonlibCrond'

第四步: 配置计划任务配置文件
这一步需要大家注意,由于这个属于tp5配置文件,tp5.0 和 tp5.01之后的配置文件存放位置不一样,大家根据自己版本调整。在applicationextracrond.php文件中

<?php

$crond_list = array(
'*' => [
'appcommandTest::firstTest'
], //每分钟

'00:00' => [], //每周 ------------
'*-01 00:00' => [], //每月--------
'*:00' => [], //每小时---------

);

return $crond_list;

这个配置文件跟第一步配置相关联的,配置的是某个具体的类和方法,主要一点要指定具体的命名空间和方法名,建议用静态方法,省去new对象,节省资源。方法名不要带(),否则执行不成功。
计划任务的执行命令行:cmd 打开到项目根目录

php think Cron

计划任务就这样实现了。最后就是部署到系统的计划任务中。让系统每分钟执行这个命令。

linux下面的crontab配置教程:

先在项目根目录创建一个crond.sh的执行文件,输入下面的内容(加上php程序的目录)

#!/bin/sh
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
cd /htdocs/baiben/www/
php think Cron

开放执行权限:chmond u+x crond.sh
然后运行下面的教程,配置计划任务:
命令行:crontab -e  
然后再界面输入:*/1 * * * * bash 你的目录/crond.sh
保存退出
然后重启crond:
命令:service crond restart
完成。

原文:https://blog.csdn.net/panxiong91/article/details/52841593

原文地址:https://www.cnblogs.com/init-007/p/11347407.html