LISTEN
LISTEN — listen for a notification
Synopsis
LISTEN channel
Description
LISTEN registers the current session as a listener on the notification channel named channel. If the current session is already registered as a listener on this notification channel, nothing happens.
Whenever the command NOTIFY channel is invoked (whether in this session or in another session connected to the same database), all sessions currently listening on that notification channel will be notified, and each session will in turn notify its connected client application.
The UNLISTEN command can be used to unregister a session from a given notification channel. When a session ends, its listener registrations are automatically cleaned up.
The method by which a client application detects notification events depends on the Halo application programming interface it uses. If the libpq library is used, the application issues LISTEN as a regular SQL command and then must periodically call the function PQnotifies to check whether any notification events have been received. Other interfaces such as libpgtcl provide higher-level methods for handling notification events. In fact, with libpgtcl, application programmers do not even need to issue LISTEN or UNLISTEN directly. For more details, consult the documentation for the interface being used.
Parameters
channel
The name of a notification channel (any identifier).
Notes
LISTEN takes effect at transaction commit. If LISTEN or UNLISTEN is executed within a transaction that is later rolled back, the set of listened notification channels does not change.
A transaction that has executed LISTEN cannot be prepared for two-phase commit.
There is a race condition when first setting up a listening session: if concurrently committed transactions are sending notification events, which events will the new listening session receive? The answer is that the session will receive all events committed after the moment in the transaction commit step. However, this is later than any database state that the transaction might have observed in its queries. This leads to the following rule for using LISTEN: first execute (and commit!) the command, then check the database state in a new transaction as needed by the application logic, and then rely on notifications to learn about subsequent changes to the database state. The first few notifications received may refer to updates that were already observed during the initial database check, but this is typically harmless.
NOTIFY provides a more extensive discussion of the use of LISTEN and NOTIFY.
Examples
# Configure and execute a listen/notify sequence from psql
LISTEN virtual;
NOTIFY virtual;
Asynchronous notification "virtual" received from server process with PID 8448.
See Also
NOTIFY, UNLISTEN