Sending Events¶
pgrelay.notify() is how you fire an event. Call it anywhere you would call a regular PostgreSQL function — from a trigger, an application, another function, or directly in psql (PostgreSQL's command-line client).
-- Basic usage:
SELECT pgrelay.notify('my_channel', 'payload text');
-- No payload (defaults to an empty string):
SELECT pgrelay.notify('my_channel');
The event is written to the queue inside your current transaction. This means:
- If your transaction commits, the event is saved and will be processed.
- If your transaction rolls back, the event is discarded as if it never happened.
Scheduling an event for the future¶
-- Run at 2 AM tomorrow:
SELECT pgrelay.notify('nightly_report', '',
p_run_at := date_trunc('day', now() + interval '1 day') + interval '2 hours');
Setting an expiry¶
If the event has not been processed by the deadline you set, it is discarded rather than run. This is useful for time-sensitive events, where running the action late would be worse than not running it at all.
-- Discard if not processed within 5 minutes:
SELECT pgrelay.notify('flash_sale_open', sale_id::text,
p_expire_at := now() + interval '5 minutes');
Suppressing duplicates¶
If several notifications are fired before the Processor gets to them, you can — optionally — suppress redundant events so only one actually runs.
-- Only one un-processed event per product in the queue at a time:
PERFORM pgrelay.notify('product_changed', NEW.product_id::text,
p_deduplicate := true);
What happens if the channel name is wrong?¶
notify() checks that the channel is registered before writing anything. A mistyped name raises an error immediately:
This catches mistakes at the point you called notify(), rather than silently creating an event that would never be processed.
Now that you can fire events, continue to Managing Channels to learn how to register, update, and monitor the channels those events run against.