diff --git a/examples/timers.php b/examples/timers.php new file mode 100644 index 0000000..883b110 --- /dev/null +++ b/examples/timers.php @@ -0,0 +1,54 @@ +pushContext($context); + $this->updatePrompt(); + + $this->addTimer(5000, function () { + echo "5 seconds\n"; + }); + } + + protected function updatePrompt() + { + $this->setPrompt("test[{$this->seq}]: "); + } + + protected function onCommand($buffer) + { + $this->seq++; + $this->updatePrompt(); + parent::onCommand($buffer); + } + +} + +$myShell = new MyShell(); +$myShell->run(); +echo "Exiting\n"; diff --git a/lib/Shell.php b/lib/Shell.php index 3b9c075..dd4e787 100644 --- a/lib/Shell.php +++ b/lib/Shell.php @@ -16,6 +16,8 @@ class Shell protected $contextStack = []; protected $listeners = []; + + protected $timers = []; public function __construct() { @@ -126,7 +128,26 @@ class Shell */ public function addTimer($interval, callable $handler, array $userdata=[]) { - + $timer = new class($interval, $handler, $userdata) { + private $next; + private $interval; + private $handler; + private $userdata; + public function __construct($interval, callable $handler, array $userdata) { + $this->interval = $interval / 1000; + $this->handler = $handler; + $this->userdata = $userdata; + } + public function update() { + $now = microtime(true); + if ($now > $this->next) { + $this->next = $now + $this->interval; + call_user_func($this->handler, $this->userdata); + } + } + }; + $this->timers[] = $timer; + return $timer; } /** @@ -287,6 +308,9 @@ class Shell // Execute the buffer ob_start(); $this->dispatchEvent("update"); + foreach ($this->timers as $timer) { + $timer->update(); + } if ($buffer) { $this->executeBuffer($buffer); }