tp 实现定时任务

这里我是用tp6进行测试的:适合做本地项目

博客参考::

https://www.thinkphp.cn/topic/64455.html

1:composer  安装workman插件

composer require workerman/workerman

2:创建 Timer 命令

php think make:command Timer

3:此时app/command就会生成一个php文件,我们再这里进行写定时任务代码即可;

 

 复制代码;

class SelfTimer extends Command
{
    protected $timer;
    protected $interval = 10;

    protected function configure()
    {
        // 指令配置
        $this->setName('timer')
            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon(守护进程)方式启动')
            ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次')
            ->setDescription('开启/关闭/重启 定时任务');
    }

    protected function init(Input $input, Output $output)
    {
        global $argv;
        if ($input->hasOption('i'))
            $this->interval = floatval($input->getOption('i'));
        $argv[1] = $input->getArgument('status') ?: 'start';
        if ($input->hasOption('d')) {
            $argv[2] = '-d';
        } else {
            unset($argv[2]);
        }
    }

    protected function execute(Input $input, Output $output)
    {

        $this->init($input, $output);
        //创建定时器任务
        $task = new Worker();
        $task->count = 1;
        $task->onWorkerStart = [$this, 'start'];
        $task->runAll();
    }

    public function stop()
    {
        //手动暂停定时器
        \Workerman\Lib\Timer::del($this->timer);
    }

    public function start()
    {
        $last = time();
        $task = [6 => $last, 10 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
        $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
            //可以在这里写你想要实现的功能
          $data= "这是测试任务";
          $path=public_path().rand(1,333).'.'.'html';
          file_put_contents($path,$data);
        });
    }
}

 

 我这里的定时任务是在文件public 下随机生成一个.txr文件进行测试

 

 4:注册 Timer 命令

修改config/console.php 文件

<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
        'timer'=>\app\command\SelfTimer::class
    ],
];

5:启动定时器

  1. php think timer start
查看执行的代码:

 

 效果图:

 

 

6:关闭定时器

  1. php think timer stop

 

posted @ 2022-03-05 17:39  王越666  阅读(463)  评论(0编辑  收藏  举报