I am using pika.BlockingConnection
in a consumer which performs some tasks for each message. I have also added signal handling so that the consumer dies properly after completely performing all tasks.
While message is being processed and signal is received, I just get "signal received"
from the function, but the code does not exit. So, I decided to check for signal received at the end of callback function, too. The question is, how many times do I check for the signal, as there will be many more functions in this code. Is there a better way of handling signals without overdoing things?
import signal
import sys
import pika
from time import sleep
received_signal = False
all_over = False
def signal_handler(signal, frame):
global received_signal
print "signal received"
received_signal = True
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
mq_connection = pika.BlockingConnection(pika.ConnectionParameters(my_mq_server, virtual_host='test'))
mq_channel = mq_connection.channel()
def callback(ch, method, properties, body):
if received_signal:
print "Exiting, as a kill signal is already received"
exit(0)
print body
sleep(50)
mq_channel.basic_ack(delivery_tag=method.delivery_tag)
print "Message consumption complete"
if received_signal:
print "Exiting, as a kill signal is already received"
exit(0)
try:
print ' [*] Waiting for messages. To exit press CTRL+C'
mq_channel.basic_consume(callback, queue='test')
mq_channel.start_consuming()
except Exception:
mq_channel.close()
exit()
This is my first question here, so let me know if any more details are required.
signal_handler
method just callsys.exit(0)
directly? – Cesarean