Skip to content

Instantly share code, notes, and snippets.

@sharavsambuu
Forked from dtheodor/listen_pg.py
Created June 26, 2020 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharavsambuu/4a1fe3e75754b4aa009dd89c422bf637 to your computer and use it in GitHub Desktop.
Save sharavsambuu/4a1fe3e75754b4aa009dd89c422bf637 to your computer and use it in GitHub Desktop.
Listen for pg_notify with Psycopg2
import select
import datetime
import psycopg2
import psycopg2.extensions
conn = psycopg2.connect(database="postgres", user="vagrant")
#conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN test;")
curs.execute("LISTEN lol;")
seconds_passed = 0
print "Waiting for notifications on channel 'test'"
while 1:
conn.commit()
if select.select([conn],[],[],5) == ([],[],[]):
seconds_passed += 5
print "{} seconds passed without a notification...".format(seconds_passed)
else:
seconds_passed = 0
conn.poll()
conn.commit()
while conn.notifies:
notify = conn.notifies.pop()
print "Got NOTIFY:", datetime.datetime.now(), notify.pid, notify.channel, notify.payload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment