1
0
mirror of https://github.com/danog/postgres.git synced 2024-12-02 09:27:54 +01:00
postgres/examples/multi-listen.php

66 lines
1.9 KiB
PHP
Raw Normal View History

2017-07-29 17:28:20 +02:00
#!/usr/bin/env php
<?php
2018-07-01 19:33:12 +02:00
require \dirname(__DIR__) . '/vendor/autoload.php';
2017-07-29 17:28:20 +02:00
use Amp\Iterator;
use Amp\Loop;
use Amp\Postgres;
Loop::run(function () {
2018-10-15 17:44:40 +02:00
$config = Postgres\ConnectionConfig::fromString('host=localhost user=postgres');
2018-10-14 17:48:07 +02:00
2018-10-15 17:44:40 +02:00
$pool = Postgres\pool($config);
2017-07-29 17:28:20 +02:00
$channel1 = "test1";
$channel2 = "test2";
/** @var \Amp\Postgres\Listener $listener1 */
$listener1 = yield $pool->listen($channel1);
2018-07-01 19:33:12 +02:00
\printf("Listening on channel '%s'\n", $listener1->getChannel());
2017-07-29 17:28:20 +02:00
/** @var \Amp\Postgres\Listener $listener2 */
$listener2 = yield $pool->listen($channel2);
2018-07-01 19:33:12 +02:00
\printf("Listening on channel '%s'\n", $listener2->getChannel());
2017-07-29 17:28:20 +02:00
Loop::delay(6000, function () use ($listener1) { // Unlisten in 6 seconds.
2018-07-01 19:33:12 +02:00
\printf("Unlistening from channel '%s'\n", $listener1->getChannel());
2017-07-29 17:28:20 +02:00
return $listener1->unlisten();
});
Loop::delay(4000, function () use ($listener2) { // Unlisten in 4 seconds.
2018-07-01 19:33:12 +02:00
\printf("Unlistening from channel '%s'\n", $listener2->getChannel());
2017-07-29 17:28:20 +02:00
return $listener2->unlisten();
});
Loop::delay(1000, function () use ($pool, $channel1) {
return $pool->notify($channel1, "Data 1.1");
});
Loop::delay(2000, function () use ($pool, $channel2) {
return $pool->notify($channel2, "Data 2.1");
});
Loop::delay(3000, function () use ($pool, $channel2) {
return $pool->notify($channel2, "Data 2.2");
});
Loop::delay(5000, function () use ($pool, $channel1) {
return $pool->notify($channel1, "Data 1.2");
});
$iterator = Iterator\merge([$listener1, $listener2]); // Merge both listeners into single iterator.
while (yield $iterator->advance()) {
$notification = $iterator->getCurrent();
2018-07-01 19:33:12 +02:00
\printf(
2017-07-29 17:28:20 +02:00
"Received notification from PID %d on channel '%s' with payload: %s\n",
$notification->pid,
$notification->channel,
$notification->payload
);
}
});