thinkphp6创建并设置执行定时任务的方法
发表于:2022-03-11 08:36:36浏览:4271次
我们在日常的项目中开发中,总是会遇到需要将某个任务方法定时执行的需求,接下来就为大家讲述基于ThinkPHP6框架的定时执行任务的三个方案,具体的方法会在下面进行详细的描述。
方案一
使用think-cron类库
//composer 安装
composer require yunwuxin/think-cron
github文档地址: https://github.com/yunwuxin/think-cron
1.创建任务类
<?php
namespace app\task;
use yunwuxin\cron\Task;
class DemoTask extends Task
{
public function configure()
{
$this->daily(); //设置任务的周期,每天执行一次,更多的方法可以查看源代码,都有注释
}
/**
* 执行任务
* @return mixed
*/
protected function execute()
{
//...具体的任务执行
}
}
2.配置文件 application/extra/cron.php
return [
'tasks' => [
\app\task\DemoTask::class, //任务的完整类名
]
];
3.开启任务监听
方法一 (推荐)
起一个常驻进程,可以配合supervisor使用
php think cron:schedule
方法二
在系统的计划任务里添加
php /path/to/think cron:run >> /dev/null 2>&1
方案二
自己手写方法。
1.在app下创建command文件夹,写一个timedTask.php文件,如下图:
<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;
class timedTask extends Command
{
protected function configure(){
$this->setName('SendMessage')->setDescription("计划任务 SendMessage");
}
//调用SendMessage 这个类时,会自动运行execute方法
protected function execute(Input $input, Output $output){
$output->writeln('Date Crontab job start...');
/*** 这里写计划任务列表集 START ***/
$this->test();
/*** 这里写计划任务列表集 END ***/
$output->writeln('Date Crontab job end...');
}
//获取当天生日的员工 发短信
public function test()
{
Db::name('log')->insert([
'content' => '定时发起',
'add_time' => time(),
'uid' => 1,
'code' => '1000',
'title' => '定时任务'
]);
//echo '这里写你要实现的逻辑代码';
}
}
?>
2.在app/command.php里面加上
return ['app\command\timedTask'];
3.运行SendMessage命令,查看代码是否可运行
进入服务器,进入项目目录,执行命令:
php think SendMessage
设置crontab计划任务
服务器无宝塔,注:
crontab -l //计划任务列表
crontab -e //编辑新增
crontab -r //删除
执行crontab -e,添加下面的定时任务,每隔1分钟执行一次后面的命令
php 项目路径/think 设置的命令关键字
方案三
服务器安装宝塔面板,直接添加计划任务就可以了。