1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Zenstruck\ScheduleBundle\Schedule\Extension\Handler; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Lock\LockFactory; |
6
|
|
|
use Symfony\Component\Lock\PersistingStoreInterface; |
7
|
|
|
use Symfony\Component\Lock\Store\FlockStore; |
8
|
|
|
use Symfony\Component\Lock\Store\SemaphoreStore; |
9
|
|
|
use Zenstruck\ScheduleBundle\Schedule\Exception\MissingDependency; |
10
|
|
|
use Zenstruck\ScheduleBundle\Schedule\Exception\SkipTask; |
11
|
|
|
use Zenstruck\ScheduleBundle\Schedule\Extension\ExtensionHandler; |
12
|
|
|
use Zenstruck\ScheduleBundle\Schedule\Extension\WithoutOverlappingExtension; |
13
|
|
|
use Zenstruck\ScheduleBundle\Schedule\Task\TaskRunContext; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @author Kevin Bond <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
final class WithoutOverlappingHandler extends ExtensionHandler |
19
|
|
|
{ |
20
|
|
|
private $lockFactory; |
21
|
|
|
|
22
|
2 |
|
public function __construct(LockFactory $lockFactory = null) |
23
|
|
|
{ |
24
|
2 |
|
if (null === $lockFactory && !\class_exists(LockFactory::class)) { |
25
|
|
|
throw new MissingDependency(WithoutOverlappingExtension::getMissingDependencyMessage()); |
26
|
|
|
} |
27
|
|
|
|
28
|
2 |
|
$this->lockFactory = $lockFactory ?: new LockFactory(self::createLocalStore()); |
29
|
2 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param WithoutOverlappingExtension $extension |
33
|
|
|
*/ |
34
|
2 |
|
public function filterTask(TaskRunContext $context, object $extension): void |
35
|
|
|
{ |
36
|
2 |
|
if (!$extension->acquireLock($this->lockFactory, $context->getTask()->getId())) { |
37
|
1 |
|
throw new SkipTask('Task running in another process.'); |
38
|
|
|
} |
39
|
2 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param WithoutOverlappingExtension $extension |
43
|
|
|
*/ |
44
|
1 |
|
public function afterTask(TaskRunContext $context, object $extension): void |
45
|
|
|
{ |
46
|
1 |
|
$extension->releaseLock(); |
47
|
1 |
|
} |
48
|
|
|
|
49
|
1 |
|
public function supports(object $extension): bool |
50
|
|
|
{ |
51
|
1 |
|
return $extension instanceof WithoutOverlappingExtension; |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
private static function createLocalStore(): PersistingStoreInterface |
55
|
|
|
{ |
56
|
1 |
|
if (SemaphoreStore::isSupported()) { |
57
|
1 |
|
return new SemaphoreStore(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return new FlockStore(); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|