1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole\Task; |
4
|
|
|
|
5
|
|
|
use Swoole\Timer; |
6
|
|
|
|
7
|
|
|
abstract class BaseTask |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* The number of seconds before the task should be delayed. |
11
|
|
|
* |
12
|
|
|
* @var int|null |
13
|
|
|
*/ |
14
|
|
|
protected $delay; |
15
|
|
|
|
16
|
|
|
public function delay($delay) |
17
|
|
|
{ |
18
|
|
|
if ($delay !== null && $delay <= 0) { |
19
|
|
|
throw new \InvalidArgumentException('The delay must be greater than 0'); |
20
|
|
|
} |
21
|
|
|
$this->delay = $delay; |
22
|
|
|
return $this; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Delay in seconds, null means no delay. |
27
|
|
|
* @return int|null |
28
|
|
|
*/ |
29
|
|
|
public function getDelay() |
30
|
|
|
{ |
31
|
|
|
return $this->delay; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Deliver a task |
36
|
|
|
* @param mixed $task The task object |
37
|
|
|
* @return bool|mixed |
38
|
|
|
*/ |
39
|
|
|
protected function task($task) |
40
|
|
|
{ |
41
|
|
|
$deliver = function () use ($task) { |
42
|
|
|
/**@var \Swoole\Http\Server $swoole */ |
43
|
|
|
$swoole = app('swoole'); |
44
|
|
|
if ($swoole->taskworker) { |
45
|
|
|
$taskWorkerNum = isset($swoole->setting['task_worker_num']) ? (int)$swoole->setting['task_worker_num'] : 0; |
46
|
|
|
if ($taskWorkerNum < 2) { |
47
|
|
|
throw new \InvalidArgumentException('LaravelS: async task needs to set task_worker_num >= 2'); |
48
|
|
|
} |
49
|
|
|
$workerNum = isset($swoole->setting['worker_num']) ? $swoole->setting['worker_num'] : 0; |
50
|
|
|
$totalNum = $workerNum + $taskWorkerNum; |
51
|
|
|
|
52
|
|
|
$getAvailableId = function ($startId, $endId, $excludeId) { |
53
|
|
|
$ids = range($startId, $endId); |
54
|
|
|
$ids = array_flip($ids); |
55
|
|
|
unset($ids[$excludeId]); |
56
|
|
|
return array_rand($ids); |
57
|
|
|
}; |
58
|
|
|
$availableId = $getAvailableId($workerNum, $totalNum - 1, $swoole->worker_id); |
59
|
|
|
return $swoole->sendMessage($task, $availableId); |
60
|
|
|
} else { |
61
|
|
|
$taskId = $swoole->task($task); |
62
|
|
|
return $taskId !== false; |
63
|
|
|
} |
64
|
|
|
}; |
65
|
|
|
if ($this->delay !== null && $this->delay > 0) { |
66
|
|
|
Timer::after($this->delay * 1000, $deliver); |
67
|
|
|
return true; |
68
|
|
|
} else { |
69
|
|
|
return $deliver(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |