&reftitle.examples;
Simple timers
stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});
// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo "Callback of a timer created as stopped\n";
// Stop the watcher after 2 iterations
Ev::iteration() >= 2 and $w->stop();
});
// Loop until Ev::stop() is called or all of watchers stop
Ev::run();
// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);
echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);
$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>
]]>
&example.outputs.similar;
Periodic timer. Tick each 10.5 seconds
]]>
Periodic timer. Use reschedule callback
]]>
Periodic timer. Tick every 10.5 seconds starting at now
]]>
Wait until STDIN is readable
]]>
Use some async I/O to access a socket
stop();
// Stop write watcher
$w->stop();
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: google.co.uk\r\n";
$in .= "Connection: Close\r\n\r\n";
if (!socket_write($socket, $in, strlen($in))) {
trigger_error("Failed writing $in to socket", E_USER_ERROR);
}
$read_watcher = new EvIo($socket, Ev::READ, function ($w, $re)
use ($socket, $e_nonblocking)
{
// Socket is readable. recv() 20 bytes using non-blocking mode
$ret = socket_recv($socket, $out, 20, MSG_DONTWAIT);
if ($ret) {
echo $out;
} elseif ($ret === 0) {
// All read
$w->stop();
socket_close($socket);
return;
}
// Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
if (in_array(socket_last_error(), $e_nonblocking)) {
return;
}
$w->stop();
socket_close($socket);
});
Ev::run();
});
$result = socket_connect($socket, $address, $service_port);
Ev::run();
?>
]]>
&example.outputs.similar;
Embedding one loop into another
]]>
Embedding loop created with kqueue backend into the default loop
]]>
Handle SIGTERM signal
stop();
});
Ev::run();
?>
]]>
Monitor changes of /var/log/messages
attr();
if ($attr['nlink']) {
printf("Current size: %ld\n", $attr['size']);
printf("Current atime: %ld\n", $attr['atime']);
printf("Current mtime: %ld\n", $attr['mtime']);
} else {
fprintf(STDERR, "`messages` file is not there!");
$w->stop();
}
});
Ev::run();
?>
]]>
Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay
stop();
$stat = $w->data;
// 1 second after the most recent change of the file
printf("Current size: %ld\n", $stat->attr()['size']);
});
$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
// Reset timer watcher
$timer->again();
});
$timer->data = $stat;
Ev::run();
?>
]]>
Process status changes
stop();
printf("Process %d exited with status %d\n", $w->rpid, $w->rstatus);
});
Ev::run();
// Protect against Zombies
pcntl_wait($status);
} else {
//Forked child
exit(2);
}
?>
]]>