CronRunBehavior.class.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. use Think\Log as Log;
  16. class CronRunBehavior
  17. {
  18. public function run(&$params)
  19. {
  20. // 锁定自动执行
  21. $lockfile = RUNTIME_PATH . 'cron.lock';
  22. if (is_writable($lockfile) && filemtime($lockfile) > $_SERVER['REQUEST_TIME'] - C('CRON_MAX_TIME', null, 60)) {
  23. return;
  24. } else {
  25. touch($lockfile);
  26. }
  27. set_time_limit(1000);
  28. ignore_user_abort(true);
  29. // 载入cron配置文件
  30. // 格式 return array(
  31. // 'cronname'=>array('filename',intervals,nextruntime),...
  32. // );
  33. if (is_file(RUNTIME_PATH . '~crons.php')) {
  34. $crons = include RUNTIME_PATH . '~crons.php';
  35. } elseif (is_file(COMMON_PATH . 'Conf/crons.php')) {
  36. $crons = include COMMON_PATH . 'Conf/crons.php';
  37. }
  38. if (isset($crons) && is_array($crons)) {
  39. $update = false;
  40. $log = array();
  41. foreach ($crons as $key => $cron) {
  42. if (empty($cron[2]) || $_SERVER['REQUEST_TIME'] >= $cron[2]) {
  43. // 到达时间 执行cron文件
  44. G('cronStart');
  45. include COMMON_PATH . 'Cron/' . $cron[0] . '.php';
  46. G('cronEnd');
  47. $_useTime = G('cronStart', 'cronEnd', 6);
  48. // 更新cron记录
  49. $cron[2] = $_SERVER['REQUEST_TIME'] + $cron[1];
  50. $crons[$key] = $cron;
  51. $log[] = "Cron:$key Runat " . date('Y-m-d H:i:s') . " Use $_useTime s\n";
  52. $update = true;
  53. }
  54. }
  55. if ($update) {
  56. // 记录Cron执行日志
  57. \Think\Log::write(implode('', $log));
  58. // 更新cron文件
  59. $content = "<?php\nreturn " . var_export($crons, true) . ";\n?>";
  60. file_put_contents(RUNTIME_PATH . '~crons.php', $content);
  61. }
  62. }
  63. // 解除锁定
  64. unlink($lockfile);
  65. return;
  66. }
  67. }