worker2.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env python3
  2. import pika
  3. import time
  4. connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
  5. channel = connection.channel()
  6. channel.queue_declare(queue="task_queue", durable=True)
  7. print(" [*] Waiting for messages. To exit press CTRL+C")
  8. heart = 0
  9. def callback(ch, method, properties, body):
  10. global heart
  11. # instead of b'Hello World!'
  12. text = body.decode("utf-8")
  13. print(" [x] Received", text)
  14. time.sleep(text.count("."))
  15. print(" [x] Done")
  16. heart = time.time()
  17. ch.basic_ack(delivery_tag=method.delivery_tag)
  18. channel.basic_qos(prefetch_count=1)
  19. channel.basic_consume(queue="task_queue", on_message_callback=callback)
  20. # channel.start_consuming()
  21. delay = 60
  22. while channel._consumer_infos:
  23. channel.connection.process_data_events(time_limit=delay)
  24. print("delay=", delay, "heart=", heart, "clock=", time.time());
  25. if ( heart == 0 ):
  26. if delay != 60:
  27. delay = 60
  28. print("Deep sleep...")
  29. else:
  30. delay = 10
  31. delta = time.time() - heart
  32. print("delta=", delta)
  33. if (delta > 50):
  34. print("ZZZzzz...")
  35. heart = 0
  36. connection.close()