EasySwoole 定时器(上)定时任务的使用

EasySwoole版本:3.3.4

好处:免去了在Linux中编写的不直观。
缺点:只能精确到秒,下文中,用毫秒定时器解决。

第一步:调用

在主进程中注册,调用

use App\Crontab\TaskOne;
use EasySwoole\EasySwoole\Crontab\Crontab;

public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.
        /**
         * **************** Crontab任务计划 **********************
         */
        // 开始一个定时任务计划 
        Crontab::getInstance()->addTask(TaskOne::class);
    }

第二步:编写


/**
 * 一个EasySwoole定时任务例子
 */

namespace App\Crontab;


use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\Task\TaskManager;

class TaskOne extends AbstractCronTask
{

    public static function getRule(): string
    {
        return '*/1 * * * *';
    }

    public static function getTaskName(): string
    {
        return  'taskOne';
    }

    function run(int $taskId, int $workerIndex)
    {
        TaskManager::getInstance()->async(function () use ($taskId, $workerIndex) {
        //执行后,终端打印如下:Test Crontab and taskId:1 ; workerIndex: 0 ;
            echo "Test Crontab and taskId:{$taskId} ; workerIndex: {$workerIndex} ;";
            
        });
    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        echo $throwable->getMessage();
    }
}


发布了103 篇原创文章 · 获赞 81 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/yuhezheg/article/details/104132501