PageRenderTime 36ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/code/classes/pinetd/Timer.class.php

https://github.com/blekkzor/pinetd2
PHP | 73 lines | 57 code | 15 blank | 1 comment | 7 complexity | 4aa1468facf520a4feb6e0db7daafa12 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. namespace pinetd;
  3. use \SplPriorityQueue;
  4. class TimerQueue extends SplPriorityQueue {
  5. public function compare($priority1, $priority2) {
  6. // Overload compare func to make it work as we expect with stamps
  7. if ($priority1 == $priority2) return 0;
  8. return ($priority1 < $priority2) ? 1 : -1;
  9. }
  10. }
  11. class Timer {
  12. private $_timers;
  13. static $self = NULL;
  14. private function __construct() {
  15. $this->_timers = new TimerQueue();
  16. }
  17. private static function instance() {
  18. if (is_null(self::$self)) self::$self = new self();
  19. return self::$self;
  20. }
  21. private function _addTimer(array $timer) {
  22. $next_run = microtime(true) + $timer['delay'];
  23. $this->_timers->insert($timer, $next_run);
  24. }
  25. public static function addTimer($callback, $delay, &$extra = null, $recurring = false) {
  26. $timer = array(
  27. 'callback' => $callback,
  28. 'delay' => $delay,
  29. 'extra' => &$extra,
  30. 'recurring' => $recurring,
  31. );
  32. self::instance()->_addTimer($timer);
  33. }
  34. private function _processTimer($timer) {
  35. $res = call_user_func($timer['callback'], &$timer['extra']);
  36. if (($timer['recurring']) && ($res))
  37. $this->_addTimer($timer);
  38. }
  39. private function _processTimers() {
  40. if (!$this->_timers->valid()) return;
  41. $now = microtime(true);
  42. $this->_timers->setExtractFlags(SplPriorityQueue::EXTR_PRIORITY);
  43. while(($this->_timers->valid()) && ($this->_timers->top() < $now)) {
  44. $this->_timers->setExtractFlags(SplPriorityQueue::EXTR_DATA);
  45. $this->_processTimer($this->_timers->extract());
  46. $this->_timers->setExtractFlags(SplPriorityQueue::EXTR_PRIORITY);
  47. }
  48. }
  49. public static function processTimers() {
  50. self::instance()->_processTimers();
  51. }
  52. private function _reset() {
  53. $this->_timers = new TimerQueue();
  54. }
  55. public static function reset() {
  56. self::instance()->_reset();
  57. }
  58. }