forked from Doomchinchilla/zKillboard
/
cron.php
114 lines (88 loc) · 2.3 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
114
#!/usr/bin/env php
<?php
if(php_sapi_name() != "cli")
die("This is a cli script!");
if(!extension_loaded('pcntl'))
die("This script needs the pcntl extension!");
$base = __DIR__;
require_once( "config.php" );
require_once( "init.php" );
interface cliCommand {
/**
* @return string
*/
public function getDescription();
/**
* @return string
*/
public function getAvailMethods();
/**
* @return void
*/
public function execute($parameters, $db);
}
$cronInfo = array();
$files = scandir("$base/cli");
foreach($files as $file)
{
if(!preg_match("/^cli_(.+)\\.php$/", $file, $match))
continue;
$command = $match[1];
$className = "cli_$command";
require_once "$base/cli/$file";
if(!is_subclass_of($className, "cliCommand"))
continue;
if(!method_exists($className, "getCronInfo"))
continue;
$class = new $className();
$cronInfo[$command] = $class->getCronInfo();
unset($class);
}
if(file_exists("$base/cron.overrides"))
{
$overrides = file_get_contents("$base/cron.overrides");
$overrides = json_decode($overrides, true);
foreach($overrides as $command => $info)
$cronInfo[$command] = $info;
}
foreach($cronInfo as $command => $info)
{
foreach($info as $interval => $arguments)
{
runCron($command, $interval, $arguments);
}
}
function runCron($command, $interval, $args)
{
global $base;
$curTime = time();
if(is_array($args))
array_unshift($args, $command);
else if($args != "")
$args = explode(" ", "$command $args");
else
$args = array($command);
$cronName = implode(".", $args);
$locker = "lastCronRun.$cronName";
$lastRun = (int)Storage::retrieve($locker, 0);
$dateFormat = "D M j G:i:s T Y";
if($curTime - $lastRun < $interval)
{
// No need to say we're not running...
return;
}
Log::log("Cron $cronName running at ".date($dateFormat, $curTime));
Storage::store($locker, $curTime);
$pid = pcntl_fork();
if($pid < 0)
{
Storage::store($locker, $lastRun);
return;
}
if($pid != 0)
return;
putenv("SILENT_CLI=1");
pcntl_exec("$base/cliLock.sh", $args);
Storage::store($locker, $lastRun);
die("Executing $command failed!");
}