Easyswoole下Crontab定時器如何實現奇偶數時間分別運行不用的定時任務
- 2020 年 3 月 6 日
- 筆記
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 AppCrontab; use EasySwooleEasySwooleCrontabAbstractCronTask; 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 AppCrontab; use EasySwooleEasySwooleCrontabAbstractCronTask; 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原創文章,轉載無需和我聯繫,但請註明來自北溟有魚QAQ https://www.umdzz.cn