0

I have written following working producer consumer code for rabbit mq in python. But I have a twist in it. The consumer is continuously putting data in the queue ever 0.5 sec but now i want my consumer to wake up every 3 sec and take all the 6 data which publisher has put in the queue and sleep back again for 3 sec. I want to go in an infinite loop for this.

But I am not sure how would i achieve this in rabbit mq

producer

import pika
import time
import datetime

connection = pika.BlockingConnection(pika.ConnectionParameters(
               'localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
value=str(int(time.time()))
for i in range (1000):
    channel.basic_publish(exchange='',routing_key='hello',body='{"action": "print", "method": "onData", "data": "Madan Mohan"}')
    time.sleep(0.5)

connection.close()

consumer

#!/usr/bin/env python
import pika
import time
import json
import datetime


connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')


def callback(ch, method, properties, body):
    #print " current time: %s "  % (str(int((time.time())*1000)))
    d=json.loads(body)
    print d

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

channel.start_consuming()
Shweta B. Patil
  • 1,131
  • 2
  • 11
  • 19

1 Answers1

2

The first solution to use sleep in callback. But probably it is not a good solution, as basic_consume is intended to get messages as faster as possible (asynchronously).

got = 0

def callback(ch, method, properties, body):
    #print " current time: %s "  % (str(int((time.time())*1000)))
    d=json.loads(body)
    print d
    got = got + 1
    if got == 6
        got = 0
        time.sleep(3)

Use channel.basic_get. It is a more appropriate solution to fetch messages synchronously.

got = 0

while True
    channel.basic_get(callback,
                      queue='hello',
                      no_ack=True)
    got = got + 1
    if got == 6
        got = 0
        time.sleep(3)
sysoff
  • 841
  • 7
  • 7