-
-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathBehavior.php
107 lines (96 loc) · 2.19 KB
/
Behavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\queue\stoppable;
use yii\caching\Cache;
use yii\di\Instance;
use yii\queue\ExecEvent;
use yii\queue\Queue;
/**
* Stoppable Behavior allows stopping scheduled jobs in a queue.
*
* It provides a [[stop()]] method to mark scheduled jobs as "stopped", that
* will prevent their execution.
*
* This behavior should be attached to the [[Queue]] component.
*
* @author Roman Zhuravlev <[email protected]>
* @since 2.0.1
*/
class Behavior extends \yii\base\Behavior
{
/**
* @var Cache|array|string the cache instance used to store stopped status.
*/
public $cache = 'cache';
/**
* @var bool option allows to turn status checking off in case a driver does not support it.
*/
public $checkWaiting = true;
/**
* @var Queue
* @inheritdoc
*/
public $owner;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->cache = Instance::ensure($this->cache, Cache::class);
}
/**
* @inheritdoc
*/
public function events()
{
return [
Queue::EVENT_BEFORE_EXEC => 'beforeExec',
];
}
/**
* @param ExecEvent $event
*/
public function beforeExec(ExecEvent $event)
{
$event->handled = $this->isStopped($event->id);
}
/**
* Sets stop flag.
*
* @param string $id of a job
* @return bool
*/
public function stop($id)
{
if (!$this->checkWaiting || $this->owner->isWaiting($id)) {
$this->markAsStopped($id);
return true;
}
return false;
}
/**
* @param string $id of a job
* @return bool
*/
protected function markAsStopped($id)
{
$this->cache->set(__CLASS__ . $id, true);
}
/**
* @param string $id of a job
* @return bool
*/
protected function isStopped($id)
{
if ($this->cache->exists(__CLASS__ . $id)) {
$this->cache->delete(__CLASS__ . $id);
return true;
}
return false;
}
}