Last active
January 28, 2025 15:06
-
-
Save ArthurDelannoyazerty/426d2aa084aad644b215b8cacbffe914 to your computer and use it in GitHub Desktop.
Small code to listen to a postgress NOTIFY while doing a normal function at the same time. No async job (except the actual listener). The NOTIFY listener is launched with asyncio in another thread while the normal job is executed in the main thread
This file contains hidden or 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 asyncio | |
import logging | |
import os | |
import psycopg2 | |
import threading | |
import time | |
from dotenv import find_dotenv, load_dotenv | |
def listen_to_notifications(): | |
try: | |
load_dotenv(find_dotenv()) | |
conn = psycopg2.connect( | |
host=os.environ.get('POSTGRES_IP'), | |
port=os.environ.get('POSTGRES_PORT'), | |
user=os.environ.get('POSTGRES_USER'), | |
password=os.environ.get('POSTGRES_PASSWORD'), | |
database=os.environ.get('POSTGRES_DB_DPMC_NAME') | |
) | |
cursor = conn.cursor() | |
cursor.execute("LISTEN channel;") # Modify the channel here | |
conn.commit() | |
def handle_notify(): | |
conn.poll() | |
for notify in conn.notifies: | |
print(notify.payload) # Your code here | |
conn.notifies.clear() | |
loop = asyncio.new_event_loop() # No event loop exist in the new thread, so we create one | |
asyncio.set_event_loop(loop) | |
loop.add_reader(conn, handle_notify) | |
loop.run_forever() | |
except KeyboardInterrupt: | |
print("Infinite loop stopped.") | |
def infinite_loop(): | |
try: | |
while True: | |
print("Executing synchronous task...") | |
time.sleep(0.4) # Simulate work | |
except KeyboardInterrupt: | |
print("Infinite loop stopped.") | |
if __name__ == "__main__": | |
notification_thread = threading.Thread(target=listen_to_notifications, daemon=False) # Daemon=False --> The thread is closed when the main thread is finicshed | |
notification_thread.start() | |
# Run the infinite loop in the main thread (simulate a job) | |
infinite_loop() # Your code here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In postgreSQL :
NOTIFY channel, 'Your data to transmit'