Easyswoole下Crontab定时器如何实现奇偶数时间分别运行不用的定时任务

Easyswoole中的定时器

  • Timer定时器,框架对原生的毫秒级定时器进行了封装(这是毫秒级)
  • Crontab定时器,EasySwoole支持用户根据Crontab规则去添加定时器,时间最小粒度是1分钟(这是分钟)

cron通用表达式

    *    *    *    *    *
    -    -    -    -    -
    |    |    |    |    |
    |    |    |    |    |
    |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
    |    |    |    +---------- month (1 - 12)
    |    |    +--------------- day of month (1 - 31)
    |    +-------------------- hour (0 - 23)
    +------------------------- min (0 - 59)

cron特殊表达式

@yearly                    每年一次 等同于(0 0 1 1 *) 
@annually                  每年一次 等同于(0 0 1 1 *)
@monthly                   每月一次 等同于(0 0 1 * *) 
@weekly                    每周一次 等同于(0 0 * * 0) 
@daily                     每日一次 等同于(0 0 * * *) 
@hourly                    每小时一次 等同于(0 * * * *)

奇数时间定时任务

<?php


namespace App\Crontab;


use EasySwoole\EasySwoole\Crontab\AbstractCronTask;

class OddNumber extends AbstractCronTask
{

    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
		//定时器表达式
        return '1-59/2 * * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
		//定时任务名称
        return  '奇数时间运行';
    }

    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
		//定时任务处理逻辑
        var_dump('奇数运行 '.date('Y-m-d H:i'));
    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
        echo $throwable->getMessage();
    }
}

偶数时间定时任务

<?php


namespace App\Crontab;


use EasySwoole\EasySwoole\Crontab\AbstractCronTask;

class EvenNumber extends AbstractCronTask
{

    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
		//定时器表达式
        return '0-58/2 * * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
		//定时任务名称
        return  '偶数时间运行';
    }

    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
		//定时任务处理逻辑
        var_dump('偶数运行 '.date('Y-m-d H:i'));
    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
		 echo $throwable->getMessage();
    }
}

添加定时计划

   public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.
        //奇数时间定时任务
        Crontab::getInstance()->addTask(OddNumber::class);
        //偶数时间定时任务
        Crontab::getInstance()->addTask(EvenNumber::class);

    }

运行 php easyswoole start 即可,效果图如下

北溟有鱼QAQ博客
请先登录后发表评论
  • 最新评论
  • 总共0条评论