-
Notifications
You must be signed in to change notification settings - Fork 14
/
SchedulerTask.php
113 lines (97 loc) · 2.76 KB
/
SchedulerTask.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
namespace webtoolsnz\scheduler\models;
use Yii;
use yii\helpers\Inflector;
/**
* This is the model class for table "scheduler_task".
*/
class SchedulerTask extends \webtoolsnz\scheduler\models\base\SchedulerTask
{
const STATUS_INACTIVE = 0;
const STATUS_PENDING = 10;
const STATUS_DUE = 20;
const STATUS_RUNNING = 30;
const STATUS_OVERDUE = 40;
const STATUS_ERROR = 50;
/**
* @var array
*/
private static $_statuses = [
self::STATUS_INACTIVE => 'Inactive',
self::STATUS_PENDING => 'Pending',
self::STATUS_DUE => 'Due',
self::STATUS_RUNNING => 'Running',
self::STATUS_OVERDUE => 'Overdue',
self::STATUS_ERROR => 'Error',
];
/**
* Return Taskname
* @return string
*/
public function __toString()
{
return Inflector::camel2words($this->name);
}
/**
* @param $task
* @return array|null|SchedulerTask|\yii\db\ActiveRecord
*/
public static function createTaskModel($task)
{
$model = SchedulerTask::find()
->where(['name' => $task->getName()])
->one();
if (!$model) {
$model = new SchedulerTask();
$model->name = $task->getName();
$model->active = $task->active;
$model->next_run = $task->getNextRunDate();
$model->last_run = NULL;
$model->status_id = self::STATUS_PENDING;
}
$model->description = $task->description;
$model->schedule = $task->schedule;
$model->save(false);
return $model;
}
/**
* @return string|null
*/
public function getStatus()
{
return isset(self::$_statuses[$this->status_id]) ? self::$_statuses[$this->status_id] : null;
}
/**
* Update the status of the task based on various factors.
*/
public function updateStatus()
{
$status = $this->status_id;
$isDue = in_array(
$status,
[
self::STATUS_PENDING,
self::STATUS_DUE,
self::STATUS_OVERDUE,
]
) && strtotime($this->next_run) <= time();
if ($isDue && $this->started_at == null) {
$status = self::STATUS_DUE;
} elseif ($this->started_at !== null) {
$status = self::STATUS_RUNNING;
} elseif ($this->status_id == self::STATUS_ERROR) {
$status = $this->status_id;
} elseif (!$isDue) {
$status = self::STATUS_PENDING;
}
if (!$this->active) {
$status = self::STATUS_INACTIVE;
}
$this->status_id = $status;
}
public function beforeSave($insert)
{
$this->updateStatus();
return parent::beforeSave($insert);
}
}