可以使用ThinkPHP中的定时任务扩展库think-scheduler来实现定时任务。以下是实现步骤:
{
"require": {
"topthink/think-scheduler": "^2.0"
}
}
执行composer update
安装依赖
在config目录下创建scheduler.php
文件,并添加以下配置:
<?php
return [
// 定时任务列表
'task_list' => [
// 每分钟执行一次
[
'name' => 'test',
'type' => 'command',
'rule' => '* * * * *',
'command' => 'test'
],
// 每天凌晨执行
[
'name' => 'clear_cache',
'type' => 'command',
'rule' => '0 0 * * *',
'command' => 'cache:clear'
],
// 自定义任务
[
'name' => 'custom_task',
'type' => 'class',
'rule' => '*/5 * * * *',
'class' => 'app\index\controller\Task',
'method' => 'run'
]
]
];
此处配置了三个定时任务,分别为每分钟执行一次的test命令、每天凌晨执行的cache:clear命令以及每5分钟执行一次的自定义任务。
php think scheduler:start
runtime/scheduler.log
使用ThinkPHP实现定时任务的步骤就是这样了。关键词如下: