From 427cac578af8f42a5d24a146d2b4f77e6bd01e01 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Wed, 2 Nov 2016 14:22:53 +0100 Subject: [PATCH] Implemented timers --- examples/timers.php | 54 +++++++++++++++++++++++++++++++++++++++++++++ lib/Shell.php | 26 +++++++++++++++++++++- 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 examples/timers.php 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); }