ThinkPHP框架应用之定时任务

本文已在本人博客https://www.nsxsg.com/archives/186首发

文章目录

  • ThinkPHP框架应用之定时任务
    • 新建一个定时类
    • 修改 `command.php` 文件
    • 查看ThinkPHP框架中定时是否添加成功
    • 运行定时任务
    • 在Linux中添加crontab

ThinkPHP框架应用之定时任务

新建一个定时类

  1. application/admin/command 目录下新建一个 Test.php 文件

  2. 文件内容如下:


namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

class Test extends Command
{
    protected function configure(){
        $this->setName('test')->setDescription("计划任务 Test");
    }

    protected function execute(Input $input, Output $output){
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/
 
        $this->test();
 
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }

    private function test()
    {
        echo '定时任务成功啦~';
    }


}

效果图如下:
ThinkPHP框架应用之定时任务_第1张图片

修改 command.php 文件

文件位置 application/command.php

  • 修改内容如下
return [
    'app\admin\command\Test'
];

效果图:
ThinkPHP框架应用之定时任务_第2张图片

查看ThinkPHP框架中定时是否添加成功

  • 进入项目目录 (并非是根目录) ,使用命令查看
php think

效果图如下:
ThinkPHP框架应用之定时任务_第3张图片

运行定时任务

php think test

效果如图:
ThinkPHP框架应用之定时任务_第4张图片

在Linux中添加crontab

  • 编辑crontab
# 编辑crontab
crontab -e

# 进入编辑模式后添加如下内容
* * * * * php /home/wwwroot/demo.com/think test    # 每分钟执行一次计划任务

# 保存退出后重启crontab
/etc/init.d/crond restart

效果图如下:
ThinkPHP框架应用之定时任务_第5张图片
image

你可能感兴趣的:(PHP,Shell,ThinkPHP框架,定时)