# herosphp-crontab **Repository Path**: blackfox/herosphp-crontab ## Basic Information - **Project Name**: herosphp-crontab - **Description**: Crontab adapter herosphp Framework - **Primary Language**: PHP - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-09-13 - **Last Updated**: 2022-09-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # herosphp/crontab 定时任务调度 ## install ```shell composer install herosphp/crontab ``` ## usage ### config/process.config.php ```php return [ //仅能1个进程 'crontab' => [ 'enable' => true, 'handler' => CrontabWorker::class ], //大量任务的时候,通过投递到异步任务完成 'async_worker' => [ 'enable' => true, 'listen' => 'tcp://127.0.0.1:8182', 'handler' => AsyncTaskWorker::class, 'count' => 1 ], ]; ``` ### CrontabWorker ```php '* * * * * *', //支持秒 'task' => [AsyncTask::class, 'run'], //处理类和执行方法 'memo' => 'say Hello' //备注可选 ] ]; /** * @param Worker $worker * @return void */ public function onWorkerStart(Worker $worker): void { foreach (static::$cronList ?? [] as $cron) { new Crontab($cron['rule'], static function () use ($cron) { static::delivery($cron['task'][0], $cron['task'][1], $cron['memo']); }); } } /** * 投递到异步进程. 一个定时任务执行比较久,间隔设置时间比较短,加锁。一个任务一个时刻仅有一个运行. * * @throws Exception */ private static function delivery(string $clazz, string $method, string $memo): void { $lock = Lock::get("{$clazz}{$method}"); if ($lock->tryLock()) { $taskConnection = new AsyncTcpConnection('tcp://127.0.0.1:8182'); $taskConnection->send(json_encode(['clazz' => $clazz, 'method' => $method])); $taskConnection->onMessage = function (AsyncTcpConnection $asyncTcpConnection, $taskResult) use ($lock) { $asyncTcpConnection->close(); $lock->unlock(); }; $taskConnection->connect(); } } } ``` ### AsyncTaskWorker ```php send('ok'); } } ```