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
|
<?php
use Illuminate\Database\Capsule\Manager as DB; use Carbon\Carbon as Carbon;
class Cronjob extends BaseModel{ protected $table = "cronjob";
private $cron;
public function __construct(){}
public function cronjobLogs(){ return $this->hasMany('CronjobLog'); }
public function _init_cron(){ if(!$this->cron){ // vdump(__FUNCTION__); $this->cron = Cron\CronExpression::factory("{$this->minute} {$this->hour} {$this->dom} {$this->mon} {$this->dow}"); } }
public function schedule($nextrundate = null, $is_recurrent = true){ $this->_init_cron(); // vdump($this->cron); if($this->is_recurrent){ $this->nextrundate = $this->cron->getNextRunDate()->format('Y-m-d H:i:s'); } return $this; }
public function pingToRun(){ $this->_init_cron();
if($this->cron->isDue() || timestamp() > $this->nextrundate){ $this->run(); } }
public function run(){ $this->_init_cron();
if($this->is_active){ $this->lastrundate = timestamp();
$cronjobLog = new CronjobLog();
try { // execute command if($this->command){ if(ends_with($this->command, '.php')){ // vdump($this->command, 'php'); ob_start(); include $this->command; $result = ob_get_clean(); // vdump("result: {$result}"); }else{ // vdump($this->command, '.fn'); $result = call_user_func_array($this->command, json_decode($this->command_arg_json)); } }
if($result){ $this->lastrun_result = $result; }else{ $this->lastrun_result = '--EMPTY--'; }
} catch (Exception $e) { $this->lastrun_result = json_encode($e) ; }
$cronjobLog->result = $this->lastrun_result;
$this->cronjobLogs()->save($cronjobLog); } // dq(1,1); $this->schedule() ->save(); }
public static function allActive(){ // TODO: rotate order if the last run halt unexpectedly preventing one error halt all jobs return self::where('nextrundate', '<=', Db::raw('NOW()')) ->where('is_active', 1) ->get(); }
public static function sampleFunction($p1=null, $p2=null){ return __FUNCTION__ . ": p1:{$p1} p2:{$p2} "; } }
|