Completed
Push — master ( 64b90d...8af03a )
by Biao
06:02
created

Task::setTimerMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Hhxsv5\LaravelS\Swoole\Task;
4
5
use Illuminate\Queue\SerializesModels;
6
7
abstract class Task
8
{
9
    use SerializesModels;
0 ignored issues
show
introduced by
The trait Illuminate\Queue\SerializesModels requires some properties which are not provided by Hhxsv5\LaravelS\Swoole\Task\Task: $class, $id
Loading history...
10
11
    /**
12
     * The number of seconds before the task should be delayed.
13
     *
14
     * @var int|null
15
     */
16
    protected $delay;
17
18
    public function delay($delay)
19
    {
20
        if ($delay <= 0) {
21
            throw new \InvalidArgumentException('The delay must be greater than 0');
22
        }
23
        if ($delay >= 86400) {
24
            throw new \InvalidArgumentException('The max delay is 86400s');
25
        }
26
        $this->delay = $delay;
27
        return $this;
28
    }
29
30
    public function getDelay()
31
    {
32
        return $this->delay;
33
    }
34
35
    abstract public function handle();
36
37
    public static function deliver(self $task, $bySendMessage = false)
38
    {
39
        $deliver = function () use ($task, $bySendMessage) {
40
            /**
41
             * @var \swoole_http_server $swoole
42
             */
43
            $swoole = app('swoole');
44
            if ($bySendMessage) {
45
                $taskWorkerNum = isset($swoole->setting['task_worker_num']) ? $swoole->setting['task_worker_num'] : 0;
46
                if ($taskWorkerNum === 0) {
47
                    throw new \InvalidArgumentException('LaravelS: Asynchronous task needs to set task_worker_num > 0');
48
                }
49
                $workerNum = isset($swoole->setting['worker_num']) ? $swoole->setting['worker_num'] : 0;
50
                $totalNum = $workerNum + $taskWorkerNum;
51
                return $swoole->sendMessage($task, mt_rand($workerNum, $totalNum - 1));
0 ignored issues
show
Bug introduced by
$task of type Hhxsv5\LaravelS\Swoole\Task\Task is incompatible with the type string expected by parameter $message of Swoole\Server::sendMessage(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
                return $swoole->sendMessage(/** @scrutinizer ignore-type */ $task, mt_rand($workerNum, $totalNum - 1));
Loading history...
52
            } else {
53
                $taskId = $swoole->task($task);
54
                return $taskId !== false;
55
            }
56
        };
57
        if ($task->delay > 0) {
58
            swoole_timer_after($task->delay * 1000, $deliver);
59
            return true;
60
        } else {
61
            return $deliver();
62
        }
63
    }
64
}