Tick.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace ModulesGarden\ProxmoxAddon\Core\CommandLine;
  3. /**
  4. * Count time between callback time. It requires declare(ticks = 1);
  5. * @package ModulesGarden\ProxmoxAddon\Core\CommandLine
  6. */
  7. class Tick
  8. {
  9. /**
  10. * @var callable
  11. */
  12. protected $callback = null;
  13. /**
  14. * @var int
  15. */
  16. protected $callbackTime = 0;
  17. /**
  18. * @var int
  19. */
  20. protected $callbackInterval = 5;
  21. /**
  22. * Tick constructor.
  23. * @param $callback
  24. * @param $time
  25. */
  26. public function __construct($callback, $time)
  27. {
  28. $this->callback = $callback;
  29. $this->callbackTime = $time;
  30. }
  31. /**
  32. *
  33. */
  34. public function start()
  35. {
  36. register_tick_function(function()
  37. {
  38. $this->tick();
  39. }, true);
  40. }
  41. /**
  42. * @return int
  43. */
  44. public function getTimeFromLastCallback()
  45. {
  46. return time() - $this->callbackTime;
  47. }
  48. /**
  49. * Call callback if time diffeence is
  50. */
  51. public function tick()
  52. {
  53. $difference = $this->getTimeFromLastCallback();
  54. if ($difference > $this->callbackInterval)
  55. {
  56. $this->callbackTime = time();
  57. $callback = $this->callback;
  58. $callback();
  59. }
  60. }
  61. }