app_example.php
trying to combine an example of RR app and Ev together. trying to use Ev to update a global variable, which is used in HTTP response.
Ev::run(Ev::RUN_NOWAIT); does not seem to have any effect.
Ev::run(); works. but Ev is done before the http request is handled. Would like to have the Ev executed periodically while http request is being handled, at the same time.
use Spiral\RoadRunner;
use Nyholm\Psr7;
include "vendor/autoload.php";
$worker = RoadRunner\Worker::create();
$psrFactory = new Psr7\Factory\Psr17Factory();
$psr7 = new RoadRunner\Http\PSR7Worker($worker, $psrFactory, $psrFactory, $psrFactory);
$global_variable = 0;
**$w = new EvTimer(2, 1, function ($w) {
global $global_variable;
$global_variable++;
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();
});
Ev::run(Ev::RUN_NOWAIT);
# Ev::run();**
while (true) {
try {
$request = $psr7->waitRequest();
if (!($request instanceof \Psr\Http\Message\ServerRequestInterface)) { // Termination request received
break;
}
} catch (Exception $ex) {
$psr7->respond(new Psr7\Response(400)); // Bad Request
continue;
}
try {
// Application code logic
$psr7->respond(new Psr7\Response(200, [], 'Hello RoadRunner!' . $global_variable));
} catch (Exception $ex) {
$psr7->respond(new Psr7\Response(500, [], 'Something Went Wrong!'));
}
}
<?php
use React\EventLoop\Loop;
require __DIR__ . '/vendor/autoload.php';
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
return React\Http\Message\Response::plaintext(
"Hello World!\n"
);
});
$socket = new React\Socket\SocketServer('127.0.0.1:8080');
$http->listen($socket);
echo "Server running at http://127.0.0.1:8080" . PHP_EOL;
Loop::addPeriodicTimer(5, function () {
$memory = memory_get_usage() / 1024;
$formatted = number_format($memory, 3).'K';
echo "Current memory usage: {$formatted}\n";
# here is my own little logic to get data from db
# to update global variables
});