thinkphp6(tp6)创建定时任务

本文中使用的thinkphp版本:thinkphp v6.0.2

本文中使用的操作系统版本:CentOS Linux release 7.6.1810 (Core)

本文中使用的PHP版本:PHP 7.3.29


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

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

php think make:command Hello

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

三、运行hello命令

php think hello

输出

hello world

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

crontab -e  # 1、编辑crontab定时任务文件

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



声明:禁止任何非法用途使用,凡因违规使用而引起的任何法律纠纷,本站概不负责。

小周博客
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

精彩评论

全部回复 0人评论 7,777人参与

loading