hyperf-view/builder/Crontab/Mutex/RedisTaskMutex.php

72 lines
1.9 KiB
PHP

<?php
/**
* MineAdmin is committed to providing solutions for quickly building web applications
* Please view the LICENSE file that was distributed with this source code,
* For the full copyright and license information.
* Thank you very much for using MineAdmin.
*
* @Author X.Mo<root@imoi.cn>
* @Link https://gitee.com/xmo/MineAdmin
*/
declare(strict_types=1);
namespace Builder\Crontab\Mutex;
use Hyperf\Redis\RedisFactory;
use Builder\Crontab\MineCrontab;
class RedisTaskMutex implements TaskMutex
{
/**
* @var RedisFactory
*/
private $redisFactory;
public function __construct(RedisFactory $redisFactory)
{
$this->redisFactory = $redisFactory;
}
/**
* Attempt to obtain a task mutex for the given crontab.
* @param MineCrontab $crontab
* @return bool
*/
public function create(MineCrontab $crontab): bool
{
return (bool) $this->redisFactory->get($crontab->getMutexPool())->set(
$this->getMutexName($crontab),
$crontab->getName(),
['NX', 'EX' => $crontab->getMutexExpires()]
);
}
/**
* Determine if a task mutex exists for the given crontab.
* @param MineCrontab $crontab
* @return bool
*/
public function exists(MineCrontab $crontab): bool
{
return (bool) $this->redisFactory->get($crontab->getMutexPool())->exists(
$this->getMutexName($crontab)
);
}
/**
* Clear the task mutex for the given crontab.
* @param MineCrontab $crontab
*/
public function remove(MineCrontab $crontab)
{
$this->redisFactory->get($crontab->getMutexPool())->del(
$this->getMutexName($crontab)
);
}
protected function getMutexName(MineCrontab $crontab): string
{
return 'framework' . DIRECTORY_SEPARATOR . 'crontab-' . sha1($crontab->getName() . $crontab->getRule());
}
}