thinkphp6(tp6)创建定时任务

使用 thinkphp6 框架中提供的命令行形式实现定时任务

一、创建一个自定义命令类文件

php think make:command Hello

会生成一个 app\command\Hello.php 命令行指令类,我们修改内容如下:

php 复制代码
<?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 Hello extends Command
{
    protected function configure()
    {
        // 指令配置
        //这里 我们 定义了一个叫 hello 的命令,到时候我们运行该hello 命令 就会执行该文件下面的execute()方法
        $this->setName('hello')
            ->setDescription('Say hello');
    }
 
    /**
     * execute()方法 就是 运行该命令行类的时候要执行的具体业务逻辑代码
     */
    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('hello world');
    }
}

二、在 config/console.php 文件中,进行注册命令

php 复制代码
<php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
    // hello就是下面要使用 php think 运行的具体命令(即 php think hello),
    // 叫什么自己随意命名,当我们运行php think hello命令后,
    // 就会执行app\command\Hello类中的execute()方法
        'hello' => 'app\command\Hello', 
    ],
];

三、运行 hello 命令

cmd 复制代码
php think hello

输出

cmd 复制代码
hello world

四、编写 crontab 定时任务文件,将 hello 命令 添加到定时任务中

关于crontab,请参考另外一篇文章:Linux crontab命令详解

cmd 复制代码
# 1、编辑crontab定时任务文件
crontab -e  

 # 2、每天21点50分执行 php think hello命令,如果定时任务执行 发生错误,则 将错误日志文件输
50 21 * * * /usr/local/php7.3/bin/php /home/wwwroot/default/tp6_blog/think hello 2> /tmp/cron_error.log  

出到 / tmp/cron_error.log 文件中

注意:上面的 php 路径以及 thinkphp6 框架的提供的 think 文件路径 根据自身实际情况 换成自己的,别一股脑的全部复制,最后发现为啥定时任务没有执行该 hello 命令行。。。

五、总结

1、输入 php think make:command Hello(类库文件名字请自行定义)

2、修改 app\command\Hello 中 execute() 方法 自己的业务逻辑代码

3、在 config/console.php 注册对应的命令

4、将命令 添加到 crontab 定时任务中

相关推荐
红红谈说19 小时前
定时发布关机就停,本地定时任务的补跑策略怎么设计?
运维·服务器·定时任务·本地调度·补跑策略·幂等互斥·执行记录
Sakura_j_h_4 天前
Python 在定时任务里输出 emoji,UnicodeEncodeError 从哪来
开发语言·字符编码·windows·python·定时任务
java_logo7 天前
Docker 部署青龙面板:轻松搭建定时任务管理平台
运维·docker·容器·定时任务·青龙面板·轩辕镜像·qinglong
要开心吖ZSH15 天前
定时任务是用外部调度(xxl-job)还是本地化( @Scheduled)更香?以号源刷新任务为例?
java·xxl-job·定时任务·scheduled
星云低代码开发平台18 天前
AI 定时任务接 ERP:账号切换后的权限校验与异常状态设计
人工智能·定时任务·erp
RuoyiOffice20 天前
SpringBoot3 企业定时结算架构:考勤日结、合同到期、库存预警与财务结转如何可靠执行
spring boot·xxl-job·定时任务·分布式任务·spring boot 3·幂等设计·ruoyi office
ZGi.ai24 天前
Agent 定时任务总跑偏?先写清触发和补跑规则
workflow·定时任务·任务调度·ai智能体·企业ai·agentruntime
晴空蓝天1 个月前
@Scheduled 定时任务不执行?八成是这 4 个问题
定时任务
szephyr1 个月前
用 Python 写自动化脚本:定时任务、文件批处理、自动出报表
python·自动化·pandas·脚本·定时任务
boomworks2 个月前
【定时执行专家】进程检测、重启、关闭功能使用说明
进程管理·定时任务·定时执行·进程重启·结束进程脚本