thinkphp主动定时任务
第一步:设置计划任务的配置
在application\config.php下面添加这个配置,
/每分钟/
/每小时 某分/
/每天 某时:某分/
/每周-某天 某时:某分 0=周日/
/每月-某天 某时:某分/
/某月-某日 某时-某分/
/某年-某月-某日 某时-某分/
‘sys_crond_timer’ => array(‘‘, ‘:i’, ‘H:i’, ‘@-w H:i’, ‘*-d H:i’, ‘m-d H:i’, ‘Y-m-d H:i’),
第二步:计划任务的核心代码。这一步已经帮大家实现了,大家需要理解的就是tp5的命令行实现就可以。在application\common\lib下面创建Crond.php文件。复制下面代码
<?php
namespace app\common\lib;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\Output;
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}()\n”;
$runtime_start = microtime(true);
call_user_func($method);
$runtime = microtime(true) - $runtime_start;
echo “{$method}(), 执行时间: {$runtime}\n\n”;
}
$time_total = microtime(true) - $GLOBALS[‘_beginTime’];
echo “total:{$time_total}\n”;
}
}
}
第三步:配置命令行
在application\command.php 添加一行。注意这个命名空间,包括上面的文件也是。如果你部署的文件夹和我不一样,需要调整一下。
‘app\common\lib\Crond’
第四步: 配置计划任务配置文件
这一步需要大家注意,由于这个属于tp5配置文件,tp5.0 和 tp5.01之后的配置文件存放位置不一样,大家根据自己版本调整。在application\extra\crond.php文件中
<?php
$crond_list = array(
‘‘ => [
‘app\command\Test::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
