Scheduler::queueJob()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 5
rs 10
cc 1
nc 1
nop 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