-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCrontab.php
113 lines (97 loc) · 2.34 KB
/
Crontab.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
108
109
110
111
112
113
<?php declare(strict_types=1);
/**
* This file is part of Swoft.
*
* @link https://swoft.org
* @document https://swoft.org/docs
* @contact [email protected]
* @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
*/
namespace Swoft\Crontab;
use Swoft;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\BeanFactory;
use Swoft\Crontab\Exception\CrontabException;
use Swoft\Timer;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
use function method_exists;
use function sprintf;
use function time;
/**
* Class Crontab
*
* @since 2.0
*
* @Bean(name="crontab")
*/
class Crontab
{
/**
* Seconds
*
* @var float
*/
private $tickTime = 1;
/**
* @var int
*/
private $maxTask = 10;
/**
* @var Channel
*/
private $channel;
/**
* Init
*/
public function init(): void
{
$this->channel = new Channel($this->maxTask);
}
/**
* Tick task
*/
public function tick(): void
{
Timer::tick($this->tickTime * 1000, function (): void {
// All task
$tasks = CrontabRegister::getCronTasks(time());
// Push task to channel
foreach ($tasks as $task) {
$this->channel->push($task);
}
});
}
/**
* Exec task
*/
public function dispatch(): void
{
while (true) {
$task = $this->channel->pop();
Coroutine::create(function () use ($task): void {
[$beanName, $methodName] = $task;
// Before
Swoft::trigger(CrontabEvent::BEFORE_CRONTAB, $this, $beanName, $methodName);
// Execute task
$this->execute($beanName, $methodName);
// After
Swoft::trigger(CrontabEvent::AFTER_CRONTAB, $this, $beanName, $methodName);
});
}
}
/**
* @param string $beanName
* @param string $method
*
* @throws CrontabException
*/
public function execute(string $beanName, string $method): void
{
$object = BeanFactory::getBean($beanName);
if (!method_exists($object, $method)) {
throw new CrontabException(sprintf('Crontab(name=%s method=%s) method is not exist!', $beanName, $method));
}
$object->$method();
}
}