1: <?php
2:
3: namespace Budabot\Core;
4:
5: 6: 7:
8: class Timer {
9: 10: 11: 12:
13: private $timerEvents = array();
14:
15: public function executeTimerEvents() {
16:
17: $time = time();
18: while (count($this->timerEvents) > 0 && $this->timerEvents[0]->time <= $time) {
19: $timerEvent = array_shift($this->timerEvents);
20: $timerEvent->callCallback();
21: }
22: }
23:
24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45:
46: public function callLater($delay, $callback) {
47: $additionalArgs = func_get_args();
48: array_shift($additionalArgs);
49: array_shift($additionalArgs);
50: return $this->addTimerEvent($delay, $callback, $additionalArgs);
51: }
52:
53: 54: 55:
56: public function abortEvent($event) {
57: $key = array_search($event, $this->timerEvents, true);
58: if ($key !== false) {
59: unset($this->timerEvents[$key]);
60: $this->sortEventsByTime();
61: }
62: }
63:
64: 65: 66:
67: public function restartEvent($event) {
68: $event->time = intval($event->delay) + time();
69: $this->sortEventsByTime();
70: }
71:
72: 73: 74: 75:
76: private function addTimerEvent($delay, $callback, $args) {
77: $event = new TimerEvent(time() + $delay, $delay, $callback, $args);
78: $this->timerEvents []= $event;
79: $this->sortEventsByTime();
80: return $event;
81: }
82:
83: private function sortEventsByTime() {
84: usort($this->timerEvents, function($a, $b) {
85: if ($a->time == $b->time) {
86: return 0;
87: }
88: return ($a->time < $b->time) ? -1 : 1;
89: });
90: }
91: }
92: