<?php
class Timer {
var $classname = "Timer";
var $start = 0;
var $stop = 0;
var $elapsed = 0;
# Constructor
function Timer( $start = true ) {
if ( $start )
$this->start();
}
# Start counting time
function start() {
$this->start = $this->_gettime();
}
# Stop counting time
function stop() {
$this->stop = $this->_gettime();
$this->elapsed = $this->_compute();
}
# Get Elapsed Time
function elapsed() {
if ( !$elapsed )
$this->stop();
return $this->elapsed;
}
# Resets Timer so it can be used again
function reset() {
$this->start = 0;
$this->stop = 0;
$this->elapsed = 0;
}
#### PRIVATE METHODS ####
# Get Current Time
function _gettime() {
$mtime = microtime();
$mtime = explode( " ", $mtime );
return $mtime[1] + $mtime[0];
}
# Compute elapsed time
function _compute() {
return $this->stop - $this->start;
}
}
?>
after
Configures the timer to trigger after after seconds.
repeat
If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;
// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
当然,我们可以使用基本的循环和 sleep()、 usleep()或 hrtime()的一些节奏轻松地创建这个函数,但是 new EvTimer()允许清理和组织多个调用,同时处理特殊情况,如 重叠。