Tick.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\Core\CommandLine;
  3. /**
  4. * Count time between callback time. It requires declare(ticks = 1);
  5. * @package ModulesGarden\Servers\ProxmoxCloudVps\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. $this->tick();
  38. }, true);
  39. }
  40. /**
  41. * @return int
  42. */
  43. public function getTimeFromLastCallback()
  44. {
  45. return time() - $this->callbackTime;
  46. }
  47. /**
  48. * Call callback if time diffeence is
  49. */
  50. public function tick()
  51. {
  52. $difference = $this->getTimeFromLastCallback();
  53. if($difference > $this->callbackInterval)
  54. {
  55. $this->callbackTime = time();
  56. $callback = $this->callback;
  57. $callback();
  58. }
  59. }
  60. }