123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146 |
- <?php
- namespace crmeb\utils;
- use think\swoole\Manager;
- use Swoole\Timer;
- use think\facade\Log;
- class Cron
- {
-
- protected $manager;
-
- protected $workerId = 0;
-
- protected $timer;
-
- protected $debug = false;
-
- public function __construct(Manager $manager)
- {
- $this->manager = $manager;
- $this->debug = env('APP_DEBUG', false);
- }
-
- public function setWorkerId(int $workerId)
- {
- $this->workerId = $workerId;
- return $this;
- }
-
- protected function runInSandbox(callable $callable)
- {
- $this->manager->runWithBarrier([$this->manager, 'runInSandbox'], function () use ($callable) {
- try {
- $callable();
- } catch (\Throwable $e) {
- $this->debug && Log::error($e->getMessage());
- }
- });
- }
-
- public function tick(int $ms, callable $callable)
- {
- if ($this->workerId === $this->manager->getWorkerId()) {
- return Timer::tick($ms, function () use ($callable) {
- $this->runInSandbox($callable);
- });
- } else {
- return null;
- }
- }
-
- public function minuteTick(string $time, callable $callable)
- {
- return $this->tick(1000 * 60, function () use ($callable, $time) {
- $nowTime = date('H:i');
- if ($nowTime === $time) {
- $callable();
- }
- });
- }
-
- public function after(int $ms, callable $callable)
- {
- Timer::after($ms, function () use ($callable) {
- $this->runInSandbox($callable);
- });
- }
-
- public function clear(int $timer)
- {
- Timer::clear($timer);
- }
-
- public function clearAll()
- {
- Timer::clearAll();
- }
- }
|