thinkphp5 定时任务

前段时间在研究thinkphp5.0版本做自动任务的时候,碰到了棘手的问题–如何做自动化任务,因为程序开始就需要一直执行,查了很多资料,都说靠php原生的死循环来做不靠谱,时间误差也没法保证,所以后面采用thinkphp5的command工具和服务器的定时任务来做:

1.新建command文件

在application/模块/新建一个command文件夹/Test.class.php

<?php
namespace app\admin\command;

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

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 "test\r\n";
    }
}

2.配置command.php文件,位置在application/command.php

<?php
return ['app\admin\command\Test'];

3.运行test命令

打开命令行,运行php think Test命令test命令execute方法中运行的方法就会运行

4.在应用根目录新建bat文件

task.bat文件

D:
cd D:\xampp\htdocs\autobet
php think Test

5.将bat文件添加到服务器计划任务

这个根据window和Linux系统不一样,定时任务设置方法也不同,可以自行百度,我用的是本地的windows服务,详情看百度经验:Windows计划任务设置,定时执行指定脚本

ps:这里设置间隔时常,可以是1分钟到31天,可选项最低是5分钟,可以手写!

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/79457849