ThinkPHP实现定时任务,tp5定时任务,thinkphp5实现秒级定时器,支持计划任务命令

浏览:10718 发布日期:2020/04/18 分类:技术分享
(1).安装tp5.0或者5.1composer create-project topthink/think=5.0.* tp5  --prefer-dist(2).安装定时任务composer包EasyTaskcomposer require easy-task/easy-task(3).创建命令行处理类文件application/common/command/Task.php<?php
namespace app\common\command;

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

class Task extends Command
{
    protected function configure()
    {
        //设置名称为task
        $this->setName('task')
            //增加一个命令参数
            ->addArgument('action', Argument::OPTIONAL, "action")
            ->addArgument('force', Argument::OPTIONAL, "force");
    }

    protected function execute(Input $input, Output $output)
    {
        //获取输入参数
        $action = trim($input->getArgument('action'));
        $force = trim($input->getArgument('force'));

        // 配置任务
        $task = new \EasyTask\Task();
        $task->setRunTimePath('./runtime/');
        $task->addFunc(function () {
            $url = 'https://www.gaojiufeng.cn/?id=319';
            file_get_contents($url);
        }, 'request', 10, 2);;

        // 根据命令执行
        if ($action == 'start')
        {
            $task->start();
        }
        elseif ($action == 'status')
        {
            $task->status();
        }
        elseif ($action == 'stop')
        {
            $force = ($force == 'force'); //是否强制停止
            $task->stop($force);
        }
        else
        {
            exit('Command is not exist');
        }
    }
}
(4).将上面创建的Task.php在配置文件application/command.php中配置一下return [
    'app\common\command\Task',
];
(5).执行命令(windows请使用cmd):php think task start  启动命令
php think task status 查询命令
php think task stop   关闭命令
php  think  task  stop  force   强制关闭命令
代码解读:        $task->addFunc(function () {
            $url = 'https://www.gaojiufeng.cn/?id=319';
            file_get_contents($url);
        }, 'request', 10, 2);;
上面的代码意思是:每隔10秒访问1次文章,开启2个进程,10s后文章被访问2次

当然我们不仅仅支持定时器还支持计划任务,例如再添加一个计划任务,支持crontab:
// 5.每晚9点半通过curl命令访问网站$task->addCommand('curl https://www.gaojiufeng.cn', 'curl', '30 21 * * *', 1);通过它你还可以实现例如每天晚上重启nginx,因为我们还支持定时执行命令。

安装环境请参考官方文档:https://gitee.com/392223903/EasyTask

请您记得给个星星支持一下,感谢您的支持,任何问题都可以在QQ群反馈。包括整合tp的过程遇到的疑问。
最佳答案
评论( 相关
后面还有条评论,点击查看>>