CronRunBehavior.class.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Behavior;
  12. /**
  13. * 自动执行任务
  14. */
  15. class CronRunBehavior {
  16. public function run(&$params) {
  17. // 锁定自动执行
  18. $lockfile = RUNTIME_PATH.'cron.lock';
  19. if(is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - C('CRON_MAX_TIME',null,60)) {
  20. return ;
  21. } else {
  22. touch($lockfile);
  23. }
  24. set_time_limit(1000);
  25. ignore_user_abort(true);
  26. // 载入cron配置文件
  27. // 格式 return array(
  28. // 'cronname'=>array('filename',intervals,nextruntime),...
  29. // );
  30. if(is_file(RUNTIME_PATH.'~crons.php')) {
  31. $crons = include RUNTIME_PATH.'~crons.php';
  32. }elseif(is_file(COMMON_PATH.'Conf/crons.php')){
  33. $crons = include COMMON_PATH.'Conf/crons.php';
  34. }
  35. if(isset($crons) && is_array($crons)) {
  36. $update = false;
  37. $log = array();
  38. foreach ($crons as $key=>$cron){
  39. if(empty($cron[2]) || $_SERVER['REQUEST_TIME']>=$cron[2]) {
  40. // 到达时间 执行cron文件
  41. G('cronStart');
  42. include COMMON_PATH.'Cron/'.$cron[0].'.php';
  43. G('cronEnd');
  44. $_useTime = G('cronStart','cronEnd', 6);
  45. // 更新cron记录
  46. $cron[2] = $_SERVER['REQUEST_TIME']+$cron[1];
  47. $crons[$key] = $cron;
  48. $log[] = "Cron:$key Runat ".date('Y-m-d H:i:s')." Use $_useTime s\n";
  49. $update = true;
  50. }
  51. }
  52. if($update) {
  53. // 记录Cron执行日志
  54. \Think\Log::write(implode('',$log));
  55. // 更新cron文件
  56. $content = "<?php\nreturn ".var_export($crons,true).";\n?>";
  57. file_put_contents(RUNTIME_PATH.'~crons.php',$content);
  58. }
  59. }
  60. // 解除锁定
  61. unlink($lockfile);
  62. return ;
  63. }
  64. }