Created
December 18, 2014 21:30
-
-
Save dtheodor/126fc329960a714f1945 to your computer and use it in GitHub Desktop.
Listen for pg_notify with Psycopg2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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