在ThinkPHP中实现定时任务处理,需要使用的是官方文档中的创建自定义指令功能。
目录
创建文件
通过think 命令行操作
php think make:command cronTest test
提示创建成功
文件内容
打开cronTest文件,可看到以下内容:
<?php
declare (strict_types = 1);
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class cronTest extends Command
{
protected function configure()
{
// 指令配置
$this->setName('test')
->setDescription('the test command');
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$output->writeln('test');
}
}
修改描述
protected function configure()
{
// 指令配置
$this->setName('test')
->setDescription('执行测试的定时任务');
}
业务处理
设置获取所有状态正常的用户并打印输出
protected function execute(Input $input, Output $output)
{
$user = Db::name('user')->where('isdel', 0)->select()->toArray();
foreach ($user as $k => $v) {
print_r($v);
}
// 指令输出
$output->writeln('test');
}
控制台配置
配置config/console.php文件
把刚才创建和编辑好的任务文件在这里注册。
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
\app\command\cronTest::class
],
];
测试-命令帮助
命令行下运行
php think
可看到有之前设置的自定义指令test。
执行任务
命令
php think test
可看到打印的用户信息,已执行成功。
命令参数
参数描述
use think\console\input\Argument;
// 必传参数
Argument::REQUIRED = 1;
// 可选参数
Argument::OPTIONAL = 2;
// 数组参数
Argument::IS_ARRAY = 4;
添加参数
指令设置中添加一个name参数
/**
* 指令配置
*/
protected function configure()
{
$this->setName('test')
->addArgument('name', Argument::OPTIONAL, "命令参数name")
->setDescription('执行测试的定时任务');
}
命令执行中接收name参数
/**
* 命令执行
* @param Input $input
* @param Output $output
* @return int|void|null
*/
protected function execute(Input $input, Output $output)
{
$name = trim($input->getArgument('name'));
$name = $name ?: '';
$output->writeln("ThinkPHP 6.1," . $name . '!');
}
执行结果
执行多个任务
可改为type参数
protected function configure()
{
$this->setName('test')
->addArgument('type', Argument::OPTIONAL, "命令参数name")
->setDescription('执行测试的定时任务');
}
在执行时通过type参数判断来分别处理
protected function execute(Input $input, Output $output)
{
$type = intval($input->getArgument('type'));
$type = $type ?: 3;
switch ($type) {
case 1:
$content = '执行任务1';
break;
case 2:
$content = '执行任务2';
break;
default:
$content = '未执行任务';
break;
}
$output->writeln("ThinkPHP 6.1," . $content . '!');
}
执行效果:
总结
至此已经结束,剩下的就是在linux中使用crontab设置定时执行了。其实还可以在控制器中调用任务,比较简单可以查看官方文档,就不再鏖述。实现与ThinkPHP5定时任务实现区别不大。