class CronRunBehavior {
public function run(&$params) {
// 载入cron配置文件
// 格式 return array(
// 'cronname'=>array('filename',intervals,nextruntime),...
// );
if (is_file ( RUNTIME_PATH . '~crons.php' ) && filemtime ( RUNTIME_PATH . '~crons.php' ) > filemtime ( CONF_PATH . 'crons.php' )) {
$crons = include RUNTIME_PATH . '~crons.php';
} elseif (is_file ( CONF_PATH . 'crons.php' )) {
$crons = include CONF_PATH . 'crons.php';
} else {
return;
}
// 锁定自动执行
$lockfile = RUNTIME_PATH . 'cron.lock';
if (is_writable ( $lockfile ) && filemtime ( $lockfile ) > $_SERVER ['REQUEST_TIME'] - C ( 'CRON_MAX_TIME', null, 60 )) {
return;
} else {
touch ( $lockfile );
}
set_time_limit ( 1000 );//脚本执行需要1000秒吗?
ignore_user_abort ( true );
if (isset ( $crons ) && is_array ( $crons )) {
$update = false;
$log = array ();
foreach ( $crons as $key => $cron ) {
if (empty ( $cron [2] ) || $_SERVER ['REQUEST_TIME'] >= $cron [2]) {
// 到达时间 执行cron文件
if (is_file ( COMMON_PATH . 'Cron/' . $cron [0] . '.php' )) {
G ( 'cronStart' );
include COMMON_PATH . 'Cron/' . $cron [0] . '.php';
$_useTime = G ( 'cronStart', 'cronEnd', 6 );
// 更新cron记录
$now = $_SERVER ['REQUEST_TIME'];
$nexttime = $cron [2] > strtotime ( 'today' ) ? $cron [2] : strtotime ( 'today' );
$intervals = $cron [1];
while ( $nexttime < $now ) {
$nexttime = $nexttime + $intervals;
}
$cron [2] = $nexttime;
$crons [$key] = $cron;
$log [] = "Cron:$key Runat " . date ( 'Y-m-d H:i:s' ) . " Use $_useTime s\n";
$update = true;
}
}
}
if ($update) {
// 记录Cron执行日志
\Think\Log::write ( implode ( '', $log ) );
// 更新cron文件
$content = "<?php\nreturn " . var_export ( $crons, true ) . ";\n?>";
file_put_contents ( RUNTIME_PATH . '~crons.php', $content );
}
}
// 解除锁定
unlink ( $lockfile );
return;
}
}
1,配置文件与缓存文件的判断2,计划脚本的判断
3,下次执行时间的误差
最佳答案
