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 定时任务中

相关推荐
码农研究僧4 天前
详细分析Mysql中的定时任务(Event事件)
数据库·mysql·定时任务·event事件
程序猿进阶8 天前
定时任务上云改造方案
java·服务器·网络·数据库·性能优化·定时任务·上云
寂寞旅行18 天前
执行分段延时轮训任务
java·开发语言·定时任务
排骨瘦肉丁1 个月前
SpringBoot中@SchedulerLock注解实现定时任务中分布式锁的使用
spring boot·分布式锁·定时任务
枫叶_v2 个月前
【SpringBoot】9 定时任务(Quartz)
java·spring boot·后端·quartz·定时任务
景天科技苑2 个月前
【python】Python中实现定时任务常见的几种方式原理分析与应用实战
开发语言·python·定时任务·python定时任务
谈谈的心情2 个月前
Java使用定时任务开始-结束活动
java·定时任务·schedule
funnyZpC3 个月前
集群及分布式定时任务中间件MEE_TIMED
java·分布式·开源·集群·定时任务
Cyclo-3 个月前
PHP 在shell服务器 创建定时任务 - thinkphp6 crontab
服务器·开发语言·php·定时任务·crontab
missterzy3 个月前
Spring Boot 创建定时任务
java·数据库·spring boot·定时任务