-
Notifications
You must be signed in to change notification settings - Fork 0
/
cron.php
113 lines (98 loc) · 2.71 KB
/
cron.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
/**
* Abstract Class cron
* Boilerplate for Cron tasks running in PHP
* Does loading and testing of permissions for log file
* Logs message to log file
* Terminates task if any errors occur
* TODO: PSR-3 / PSR Log Compliance?
*/
namespace utilities\cron;
abstract class cron
{
/**
* @var string
*/
protected $lineStart;
/**
* @var string
*/
protected $logFile;
/**
* @var bool
*/
protected $terminate = false;
/**
* cron constructor.
* @param string $logFile
* @param string $defaultTimeZone
* @param string $dateFormat
*/
public function __construct($logFile = 'error_log', $defaultTimeZone = 'America/Chicago', $dateFormat = "F j, Y, g:i a e O") {
date_default_timezone_set($defaultTimeZone);
$this->lineStart = '[ '. date($dateFormat) . ' ] Cron Log: ';
$this->logFile = $logFile;
$this->startUp();
if(!$this->terminate) {
$this->execute();
}
$this->shutDown();
}
/**
* Log
* @param string $message
*/
public function log($message) {
echo $message . PHP_EOL;
if ($this->terminate || $this->logFile === 'error_log') {
error_log($this->lineStart . $message, 0);
} else {
error_log($this->lineStart . $message . PHP_EOL, 3, $this->logFile);
}
}
/**
* Test the file for read/write/exist
* @param string $message
* @return bool
*/
protected function testLog($message = '') {
$success = false;
if ($this->logFile === 'error_log') {
$success = true;
} else if (file_exists($this->logFile)) {
if(is_writeable($this->logFile)) {
$success = true;
} else {
$this->terminate = true;
$message = "Cron log $this->logFile not writable.";
}
} else {
if(false !== file_put_contents($this->logFile, 'Log File Create on ' . date("F j, Y, g:i a e O") . PHP_EOL)) {
$success = true;
} else {
$this->terminate = true;
$message = "Cron log $this->logFile could not be created or written to.";
}
}
$this->log($message);
return $success;
}
/**
* Startup point before executing any cron code
*/
protected function startUp() {
$this->testLog('Cron Job Started.');
}
/**
* Shutdown method after execution
*/
protected function shutDown() {
$this->log('Cron Job Shutting Down.');
}
/**
* Code to be executed
*/
protected function execute() {
// Override and do code here
}
}