Skip to content

添加定时任务

liaofei edited this page Jan 20, 2021 · 1 revision

一,定时任务的具体执行方法都在:crmeb/subscribes/TaskSubscribe.php类中开发。

定时任务方法命名规则:onTask_25,每25秒执行一次此方法。


<?php
namespace crmeb\subscribes;


/**
 * 定时任务类
 * Class TaskSubscribe
 * @package crmeb\subscribes
 */
class TaskSubscribe
{
    public function handle()
    {

    }

    /**
     * 2秒钟执行的方法
     */
    public function onTask_25()
    {
        //具体业务逻辑
    }
}

二,具体定时任务方法写好后需要在时间定义文件中定义app/event.php

<?php

// 事件定义文件
return [
    'bind'      => [

    ],

    'listen'    => [

        'task_2'=>[],//2秒钟执行的方法
        'task_6'=>[],//6秒钟执行的方法
        'task_25'=>[],//25秒钟执行的方法
    ],

三,在指令启动文件中crmeb/command/Timer.php start()方法中加入25任务配置

 public function start()
    {
        $last = time();
        $task = [6 => $last, 10 => $last, 25 => $last, 30 => $last, 60 => $last, 180 => $last, 300 => $last];
        $this->timer = \Workerman\Lib\Timer::add($this->interval, function () use (&$task) {
            try {
                $now = time();
                event('Task_2');
                foreach ($task as $sec => $time) {
                    if ($now - $time >= $sec) {
                        event('Task_' . $sec);
                        $task[$sec] = $now;
                    }
                }
            } catch (\Throwable $e) {
            }
        });
    }

四,启动定时任务


php think timer [ status ] [ --d ]

参数

  • status: 状态
  • start: 启动
  • stop: 关闭
  • restart: 重启
  • --d : 后台执行

例如:

  • php think timer start --d

  • php think timer restart --d

  • php think timer stop --d

Clone this wiki locally