Cron for Windows Using PHP
Posted by: david on 11/25/2014 - 02:30 PM
Cron.php would basically just call cron_exec.php every designated X seconds (or minutes, e.g.):
$dir = "c:php";
$cmd = "c:phpphp -q " . $dir . "" . 'cron_exec.php';
$interval = 10;
do { $output = shell_exec($cmd);
$cur_time_str = date("F d, Y t h:i A");
echo "$cur_time_str: $outputnn";
write_log();
sleep($interval);
} while (TRUE) ;
function write_log() {
global $dir, $output, $cur_time_str;
$log_file = $dir . "logscron" . date("Ymd") . '.log';
$fp = fopen($log_file, 'a'); fwrite($fp, $cur_time_str . "n" . $output . "n");
fclose($fp);
}
?>
And here is the code for cron_exec.php:
<php
//cron script that executes commands
$dir = "c:\\php"; $lock_file = $dir . "" . 'cron_exec.lock';
if (file_exists($lock_file)){ die("Error: cron_exec.lock exists.n"); }
$fp = fopen($lock_file, 'w');
$result = fwrite($fp, 'cron_exec.php is running');
fclose($fp);
mysql_pconnect($host, $user_name, $password);
$q = "select min(cqid) from command_queue where executed != 'Y'";
if (!$result = mysql_query($q)){
unlink($lock_file);
die(mysql_error() . " SQL: $q");
}
list($cqid) = mysql_fetch_row($result);
if (mysql_num_rows($result) == 0 || !$cqid){
unlink($lock_file);
die("Nothing to be executed.");
}
$q = "select * from command_queue where cqid = $cqid";
if (!$result = mysql_query($q)){
unlink($lock_file);
die(mysql_error() . " SQL: $q"); }
$row = mysql_fetch_assoc($result);
$cmd = "c:\\php\php -q " . $row['command'] . ' ' . @$row['add_switch'];
$s_time = get_microtime();
$output = shell_exec($cmd);
$e_time = get_microtime();
$duration = sprintf("%01.2f", $e_time - $s_time);
$q = "update command_queue set executed = 'Y', duration = '$duration', date = sysdate() where cqid = $cqid";
if (!$result = mysql_query($q)){
unlink($lock_file);
die(mysql_error() . " SQL: $q");
}
echo "Executed $cmd, output: $output\n";
unlink($lock_file);
?>
The MySQL table would have the following structure:
+------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | cqid | int(10) unsigned | | PRI | NULL | auto_increment | | command | char(32) | YES | | NULL | | | add_switch | char(8) | YES | | NULL | | | executed | char(1) | YES | | N | | | date | datetime | YES | | NULL | | | duration | char(32) | YES | | NULL | | +------------+------------------+------+-----+---------+----------------+
I don't have the code for a front-end to edit the table because I use MysqlCC to edit it, but you can easily craft a PHP-based form to add/edit/delete jobs. Or you can simply save the tasks into a text file, and edit via notepad.