Scheduler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 9
eloc 21
c 2
b 0
f 1
dl 0
loc 79
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A queueJob() 0 5 1
A run() 0 21 5
A __construct() 0 4 1
A getQueuedJobs() 0 3 1
A clearJobs() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jellyfish\Scheduler;
6
7
use DateTime;
8
9
class Scheduler implements SchedulerInterface
10
{
11
    protected const DELAY_INTERVAL = 1000000;
12
13
    /**
14
     * @var JobInterface[]
15
     */
16
    protected $jobs;
17
18
    /**
19
     * @var JobInterface[]
20
     */
21
    protected $runningJobs = [];
22
23
    /**
24
     * Scheduler constructor
25
     */
26
    public function __construct()
27
    {
28
        $this->jobs = [];
29
        $this->runningJobs = [];
30
    }
31
32
    /**
33
     * @param \Jellyfish\Scheduler\JobInterface $job
34
     *
35
     * @return \Jellyfish\Scheduler\SchedulerInterface
36
     */
37
    public function queueJob(JobInterface $job): SchedulerInterface
38
    {
39
        $this->jobs[] = $job;
40
41
        return $this;
42
    }
43
44
    /**
45
     * @return \Jellyfish\Scheduler\SchedulerInterface
46
     */
47
    public function clearJobs(): SchedulerInterface
48
    {
49
        $this->jobs = [];
50
51
        return $this;
52
    }
53
54
    /**
55
     * @return \Jellyfish\Scheduler\SchedulerInterface
56
     *
57
     * @throws \Exception
58
     */
59
    public function run(): SchedulerInterface
60
    {
61
        $dateTime = new DateTime();
62
63
        foreach ($this->jobs as $job) {
64
            $this->runningJobs[] = $job->run($dateTime);
65
        }
66
67
        while (count($this->runningJobs) !== 0) {
68
            foreach ($this->runningJobs as $index => $runningJob) {
69
                if ($runningJob->isRunning()) {
70
                    continue;
71
                }
72
73
                unset($this->runningJobs[$index]);
74
            }
75
76
            usleep(static::DELAY_INTERVAL);
77
        }
78
79
        return $this;
80
    }
81
82
    /**
83
     * @return \Jellyfish\Scheduler\JobInterface[]
84
     */
85
    public function getQueuedJobs(): array
86
    {
87
        return $this->jobs;
88
    }
89
}
90