AbstractDaemon.class.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace KIF\Core;
  3. use KIF\Cli\SingleProcess;
  4. abstract class AbstractDaemon extends Controller {
  5. public function run() {
  6. $action = $this->action;
  7. $this->$action();
  8. }
  9. /**
  10. *
  11. * 要完成的业务逻辑,由子类实现
  12. */
  13. abstract protected function doSomething();
  14. /**
  15. *
  16. * 脚本存活时间,可由子类重写
  17. * @var int
  18. */
  19. protected $aliveTime = 7200;// 2小时
  20. /**
  21. *
  22. * Enter description here ...
  23. * @var KIF\Cli\SingleProcess
  24. */
  25. private $objSingleProcess;
  26. public function __construct() {
  27. $processId = realpath(__FILE__) . '-' . get_class($this);
  28. $timeout = 2 * $this->aliveTime;// 允许外部脚本kill当前脚本的时间,设置为存活时间的2倍。确保存活时间内,脚本不会被意外杀死。
  29. $this->objSingleProcess = new SingleProcess($processId, $timeout, true);
  30. }
  31. /**
  32. *
  33. * 判断脚本是否还能存活
  34. * @return Boolean
  35. */
  36. protected function isAlive() {
  37. static $time_init = null;
  38. if (is_null($time_init)) {
  39. $time_init = time();
  40. }
  41. $time_now = time();
  42. if ($time_now - $time_init >= $this->aliveTime) {//超过脚本的生存时间
  43. return false;
  44. }
  45. return true;
  46. }
  47. protected function doDefault() {
  48. if ($this->objSingleProcess->isRun()) {
  49. echo "已经有进程在跑了\r\n";
  50. exit();
  51. }
  52. $this->objSingleProcess->run();
  53. do {
  54. if (!$this->isAlive()) {
  55. break;
  56. }
  57. $this->doSomething();
  58. usleep(1000000);
  59. echo "休息...\r\n";
  60. } while ( true );
  61. $this->objSingleProcess->complete();
  62. echo "done\r\n";
  63. exit ();
  64. }
  65. }