Skip to content

Commit

Permalink
Merge pull request #7 from Werkint/timer-fix
Browse files Browse the repository at this point in the history
Fixes #6: ability to start/stop timer
  • Loading branch information
mkraemer committed Nov 16, 2016
2 parents a3461ce + ccf4835 commit b410b6e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 8 deletions.
48 changes: 44 additions & 4 deletions src/MKraemer/ReactPCNTL/PCNTL.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,59 @@

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\EventLoop\Timer\TimerInterface;

class PCNTL extends EventEmitter
{
const DEFAULT_INTERVAL = 0.1;

/**
* @var TimerInterface|null
*/
private $timer;
/**
* @var LoopInterface
*/
private $loop;

/**
* Constructor. Registers a periodicTimer to call
* the installed signal handlers
*
* @param \React\EventLoop\LoopInterface $loop Event Loop
* @param float $interval Interval in which new signals should be read
* @param LoopInterface $loop Event Loop
* @param float $interval Interval in which new signals should be read
*/
public function __construct(LoopInterface $loop, $interval = 0.1)
public function __construct(LoopInterface $loop, $interval = self::DEFAULT_INTERVAL)
{
$loop->addPeriodicTimer($interval, $this);
$this->loop = $loop;
$this->start($interval);
}

/**
* Adds timer to Loop queue
*
* @param float $interval
* @return TimerInterface
*/
public function start($interval = self::DEFAULT_INTERVAL)
{
if ($this->timer) {
$this->stop();
}

return $this->timer = $this->loop->addPeriodicTimer($interval, $this);
}

/**
* Cancels timer
*/
public function stop()
{
if ($this->timer && $this->timer->isActive()) {
$this->timer->cancel();
}

$this->timer = null;
}

/**
Expand Down
21 changes: 17 additions & 4 deletions test/MKraemer/ReactPCNTL/PCNTLTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace MKraemer\ReactPCNTL;

use React\EventLoop\LoopInterface;
use React\EventLoop\Timer\TimerInterface;

function pcntl_signal($signo, $callback) {
PCNTLTest::$pcntl_signal_args[$signo] = $callback;
Expand All @@ -26,13 +27,25 @@ protected function setUp()
}


public function testConstruct_addsPeriodicTimer()
public function testLoopStartStop()
{
$this->loop->expects($this->once())
$timer = $this->getMock('React\EventLoop\Timer\TimerInterface');
$this->loop->expects($this->exactly(2))
->method('addPeriodicTimer')
->with(0.1, $this->isType('callable'));
->with(0.1, $this->isType('callable'))
->willReturn($timer)
;
$timer->expects($this->once())
->method('isActive')
->willReturn(true)
;
$timer->expects($this->once())
->method('cancel')
;

new PCNTL($this->loop);
$pcntl = new PCNTL($this->loop);
$timer = $pcntl->start();
$this->assertInstanceOf('\React\EventLoop\Timer\TimerInterface', $timer);
}

public function testRegisterSignalHandler()
Expand Down

0 comments on commit b410b6e

Please sign in to comment.