在ThinkPHP框架中实现定时任务,可以使用ThinkPHP自带的定时任务扩展——ThinkPHP-Crontab。具体实现步骤如下:
composer require topthink/think-crontab
think\console\Command
,并重写configure()
和execute()
方法,如下所示:<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class MyCron extends Command
{
protected function configure()
{
$this->setName('mycron')->setDescription('My Cron Task');
}
protected function execute(Input $input, Output $output)
{
// 定时任务执行的代码
}
}
application/command.php
文件中注册定时任务类,如下所示:<?php
return [
'app\command\MyCron'
];
php think crontab
命令,启动定时任务,如下所示:php think crontab
add()
方法添加定时任务,如下所示:use think\console\command\Make;
use think\console\input\Option;
use think\console\Output;
// 添加每分钟执行一次的定时任务
$this->app->crontab->add("* * * * *", function(Output $output) {
$output->writeln('This is a cron task.');
});
需要注意的是,定时任务的时间格式使用Linux下的Crontab格式,例如* * * * *
表示每分钟执行一次。
关键词高亮:
ThinkPHP
定时任务
ThinkPHP-Crontab
composer
configure()
:configure()
execute()
:execute()
Command
:Command
Input
:Input
Output
:Output
add()
:add()
Crontab格式