Implemented timers

This commit is contained in:
Chris 2016-11-02 14:22:53 +01:00
parent ea09a15963
commit 427cac578a
2 changed files with 79 additions and 1 deletions

54
examples/timers.php Normal file
View File

@ -0,0 +1,54 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\Shell\Shell;
use NoccyLabs\Shell\Command;
use NoccyLabs\Shell\Context;
class MyContext extends Context
{
/**
* @command testme
* @args
* @help Useful test!
*/
public function test()
{
}
}
class MyShell extends Shell
{
protected $seq = 0;
protected function configure()
{
$context = new MyContext();
$this->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";

View File

@ -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);
}