Skip to content

Instantly share code, notes, and snippets.

@mgmanalili
Forked from dtheodor/listen_pg.py
Created May 11, 2018 12:30
Show Gist options
  • Save mgmanalili/87596cb1d62efd23b0f086e6aba84203 to your computer and use it in GitHub Desktop.
Save mgmanalili/87596cb1d62efd23b0f086e6aba84203 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