thinkphp6毫秒级task定时任务(后台运行)

1.Composer安装
composer require easy-task/easy-task
2. 创建类
php think make:command Task task
<?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 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'));

        // 配置任务,每隔20秒写入txt日志1次
        $task = new \EasyTask\Task();
        $task->setRunTimePath('./runtime/');
        $task->addFunc(function () {
       		file_put_contents('task_log.txt',json_encode(['date'=>date('Y-m-d H:i:s')]).PHP_EOL,FILE_APPEND);
        }, 'request', 20, 1);;

        // 根据命令执行
        if ($action == 'start')
        {
        	$task->setDaemon(true); //后台进程守护
            $task->start();
        }
        elseif ($action == 'status')
        {
            $task->status();
        }
        elseif ($action == 'stop')
        {
            $force = ($force == 'force'); //是否强制停止
            $task->stop($force);
        }
        else
        {
            exit('Command is not exist');
        }
    }
}

3.配置config\console.php文件
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
        'task' => 'app\command\Task',
    ],
];

php think task start  启动命令
php think task status 查询命令
php think task stop   关闭命令
php  think  task  stop  force   强制关闭命令
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值