Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interrupt thread with start_consuming method of pika

I have a thread which listens for new messages from rabbitmq using pika. After configuring the connection using BlockingConnection, I start consuming messages throught start_consuming. How can I interrupt the start consuming method call to, for example, stop the thread in a gracefully manner?

like image 699
arnau Avatar asked Aug 26 '15 07:08

arnau


1 Answers

You can use consume generator instead of start_consuming.

import threading

import pika


class WorkerThread(threading.Thread):
    def __init__(self):
        super(WorkerThread, self).__init__()
        self._is_interrupted = False

    def stop(self):
        self._is_interrupted = True

    def run(self):
        connection = pika.BlockingConnection(pika.ConnectionParameters())
        channel = connection.channel()
        channel.queue_declare("queue")
        for message in channel.consume("queue", inactivity_timeout=1):
            if self._is_interrupted:
                break
            if not message:
                continue
            method, properties, body = message
            print(body)

def main():
    thread = WorkerThread()
    thread.start()
    # some main thread activity ...
    thread.stop()
    thread.join()


if __name__ == "__main__":
    main()
like image 191
Slava Bezborodov Avatar answered Oct 05 '22 22:10

Slava Bezborodov