forked from peppeocchi/php-cron-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJob.php
590 lines (502 loc) · 13.1 KB
/
Job.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php namespace GO;
use DateTime;
use Exception;
use InvalidArgumentException;
class Job
{
use Traits\Interval,
Traits\Mailer;
/**
* Job identifier.
*
* @var string
*/
private $id;
/**
* Command to execute.
*
* @var mixed
*/
private $command;
/**
* Arguments to be passed to the command.
*
* @var array
*/
private $args = [];
/**
* Defines if the job should run in background.
*
* @var bool
*/
private $runInBackground = true;
/**
* Creation time.
*
* @var DateTime
*/
private $creationTime;
/**
* Job schedule time.
*
* @var Cron\CronExpression
*/
private $executionTime;
/**
* Job schedule year.
*
* @var string
*/
private $executionYear = null;
/**
* Temporary directory path for
* lock files to prevent overlapping.
*
* @var string
*/
private $tempDir;
/**
* Path to the lock file.
*
* @var string
*/
private $lockFile;
/**
* This could prevent the job to run.
* If true, the job will run (if due).
*
* @var bool
*/
private $truthTest = true;
/**
* The output of the executed job.
*
* @var mixed
*/
private $output;
/**
* The return code of the executed job.
*
* @var int
*/
private $returnCode = 0;
/**
* Files to write the output of the job.
*
* @var array
*/
private $outputTo = [];
/**
* Email addresses where the output should be sent to.
*
* @var array
*/
private $emailTo = [];
/**
* Configuration for email sending.
*
* @var array
*/
private $emailConfig = [];
/**
* A function to execute before the job is executed.
*
* @var callable
*/
private $before;
/**
* A function to execute after the job is executed.
*
* @var callable
*/
private $after;
/**
* A function to ignore an overlapping job.
* If true, the job will run also if it's overlapping.
*
* @var callable
*/
private $whenOverlapping;
/**
* @var string
*/
private $outputMode;
/**
* Create a new Job instance.
*
* @param string|callable $command
* @param array $args
* @param string $id
*/
public function __construct($command, $args = [], $id = null)
{
if (is_string($id)) {
$this->id = $id;
} else {
if (is_string($command)) {
$this->id = md5($command);
} elseif (is_array($command)) {
$this->id = md5(serialize($command));
} else {
/* @var object $command */
$this->id = spl_object_hash($command);
}
}
$this->creationTime = new DateTime('now');
// initialize the directory path for lock files
$this->tempDir = sys_get_temp_dir();
$this->command = $command;
$this->args = $args;
}
/**
* Get the Job id.
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Check if the Job is due to run.
* It accepts as input a DateTime used to check if
* the job is due. Defaults to job creation time.
* It also defaults the execution time if not previously defined.
*
* @param DateTime $date
* @return bool
*/
public function isDue(DateTime $date = null)
{
// The execution time is being defaulted if not defined
if (! $this->executionTime) {
$this->at('* * * * *');
}
$date = $date !== null ? $date : $this->creationTime;
if ($this->executionYear && $this->executionYear !== $date->format('Y')) {
return false;
}
return $this->executionTime->isDue($date);
}
/**
* Check if the Job is overlapping.
*
* @return bool
*/
public function isOverlapping()
{
return $this->lockFile &&
file_exists($this->lockFile) &&
call_user_func($this->whenOverlapping, filemtime($this->lockFile)) === false;
}
/**
* Force the Job to run in foreground.
*
* @return self
*/
public function inForeground()
{
$this->runInBackground = false;
return $this;
}
/**
* Check if the Job can run in background.
*
* @return bool
*/
public function canRunInBackground()
{
if (is_callable($this->command) || $this->runInBackground === false) {
return false;
}
return true;
}
/**
* This will prevent the Job from overlapping.
* It prevents another instance of the same Job of
* being executed if the previous is still running.
* The job id is used as a filename for the lock file.
*
* @param string $tempDir The directory path for the lock files
* @param callable $whenOverlapping A callback to ignore job overlapping
* @return self
*/
public function onlyOne($tempDir = null, callable $whenOverlapping = null)
{
if ($tempDir === null || ! is_dir($tempDir)) {
$tempDir = $this->tempDir;
}
$this->lockFile = implode('/', [
trim($tempDir),
trim($this->id) . '.lock',
]);
if ($whenOverlapping) {
$this->whenOverlapping = $whenOverlapping;
} else {
$this->whenOverlapping = function () {
return false;
};
}
return $this;
}
/**
* Compile the Job command.
*
* @return mixed
*/
public function compile()
{
$compiled = $this->command;
// If callable, return the function itself
if (is_callable($compiled)) {
return $compiled;
}
// Augment with any supplied arguments
foreach ($this->args as $key => $value) {
$compiled .= ' ' . escapeshellarg($key);
if ($value !== null) {
$compiled .= ' ' . escapeshellarg($value);
}
}
// Add the boilerplate to redirect the output to file/s
if (count($this->outputTo) > 0) {
$compiled .= ' | tee ';
$compiled .= $this->outputMode === 'a' ? '-a ' : '';
foreach ($this->outputTo as $file) {
$compiled .= $file . ' ';
}
$compiled = trim($compiled);
}
// Add boilerplate to remove lockfile after execution
if ($this->lockFile) {
$compiled .= '; rm ' . $this->lockFile;
}
// Add boilerplate to run in background
if ($this->canRunInBackground()) {
// Parentheses are need execute the chain of commands in a subshell
// that can then run in background
$compiled = '(' . $compiled . ') > /dev/null 2>&1 &';
}
return trim($compiled);
}
/**
* Configure the job.
*
* @param array $config
* @return self
*/
public function configure(array $config = [])
{
if (isset($config['email'])) {
if (! is_array($config['email'])) {
throw new InvalidArgumentException('Email configuration should be an array.');
}
$this->emailConfig = $config['email'];
}
// Check if config has defined a tempDir
if (isset($config['tempDir']) && is_dir($config['tempDir'])) {
$this->tempDir = $config['tempDir'];
}
return $this;
}
/**
* Truth test to define if the job should run if due.
*
* @param callable $fn
* @return self
*/
public function when(callable $fn)
{
$this->truthTest = $fn();
return $this;
}
/**
* Run the job.
*
* @return bool
*/
public function run()
{
// If the truthTest failed, don't run
if ($this->truthTest !== true) {
return false;
}
// If overlapping, don't run
if ($this->isOverlapping()) {
return false;
}
$compiled = $this->compile();
// Write lock file if necessary
$this->createLockFile();
if (is_callable($this->before)) {
call_user_func($this->before);
}
if (is_callable($compiled)) {
$this->output = $this->exec($compiled);
} else {
exec($compiled, $this->output, $this->returnCode);
}
$this->finalise();
return true;
}
/**
* Create the job lock file.
*
* @param mixed $content
* @return void
*/
private function createLockFile($content = null)
{
if ($this->lockFile) {
if ($content === null || ! is_string($content)) {
$content = $this->getId();
}
file_put_contents($this->lockFile, $content);
}
}
/**
* Remove the job lock file.
*
* @return void
*/
private function removeLockFile()
{
if ($this->lockFile && file_exists($this->lockFile)) {
unlink($this->lockFile);
}
}
/**
* Execute a callable job.
*
* @param callable $fn
* @throws Exception
* @return string
*/
private function exec(callable $fn)
{
ob_start();
try {
$returnData = call_user_func_array($fn, $this->args);
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
$outputBuffer = ob_get_clean();
foreach ($this->outputTo as $filename) {
if ($outputBuffer) {
file_put_contents($filename, $outputBuffer, $this->outputMode === 'a' ? FILE_APPEND : 0);
}
if ($returnData) {
file_put_contents($filename, $returnData, FILE_APPEND);
}
}
$this->removeLockFile();
return $outputBuffer . (is_string($returnData) ? $returnData : '');
}
/**
* Set the file/s where to write the output of the job.
*
* @param string|array $filename
* @param bool $append
* @return self
*/
public function output($filename, $append = false)
{
$this->outputTo = is_array($filename) ? $filename : [$filename];
$this->outputMode = $append === false ? 'w' : 'a';
return $this;
}
/**
* Get the job output.
*
* @return mixed
*/
public function getOutput()
{
return $this->output;
}
/**
* Set the emails where the output should be sent to.
* The Job should be set to write output to a file
* for this to work.
*
* @param string|array $email
* @return self
*/
public function email($email)
{
if (! is_string($email) && ! is_array($email)) {
throw new InvalidArgumentException('The email can be only string or array');
}
$this->emailTo = is_array($email) ? $email : [$email];
// Force the job to run in foreground
$this->inForeground();
return $this;
}
/**
* Finilise the job after execution.
*
* @return void
*/
private function finalise()
{
// Send output to email
$this->emailOutput();
// Call any callback defined
if (is_callable($this->after)) {
call_user_func($this->after, $this->output, $this->returnCode);
}
}
/**
* Email the output of the job, if any.
*
* @return bool
*/
private function emailOutput()
{
if (! count($this->outputTo) || ! count($this->emailTo)) {
return false;
}
if (isset($this->emailConfig['ignore_empty_output']) &&
$this->emailConfig['ignore_empty_output'] === true &&
empty($this->output)
) {
return false;
}
$this->sendToEmails($this->outputTo);
return true;
}
/**
* Set function to be called before job execution
* Job object is injected as a parameter to callable function.
*
* @param callable $fn
* @return self
*/
public function before(callable $fn)
{
$this->before = $fn;
return $this;
}
/**
* Set a function to be called after job execution.
* By default this will force the job to run in foreground
* because the output is injected as a parameter of this
* function, but it could be avoided by passing true as a
* second parameter. The job will run in background if it
* meets all the other criteria.
*
* @param callable $fn
* @param bool $runInBackground
* @return self
*/
public function then(callable $fn, $runInBackground = false)
{
$this->after = $fn;
// Force the job to run in foreground
if ($runInBackground === false) {
$this->inForeground();
}
return $this;
}
}