Advertisement
vitareinforce

simple countdown worker

Oct 30th, 2023 (edited)
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. const amqp = require('amqplib');
  2.  
  3. // RabbitMQ connection parameters
  4. const rabbitmqHost = 'amqp://TMDG2022:TMDG2022@rmq2.pptik.id:5672/';
  5. const rabbitmqQueue = 'numbers_queue';
  6.  
  7. async function connect() {
  8. try {
  9. // Connect to RabbitMQ
  10. const connection = await amqp.connect(rabbitmqHost);
  11. const channel = await connection.createChannel();
  12.  
  13. // Declare the queue
  14. await channel.assertQueue(rabbitmqQueue, {
  15. durable: true
  16. });
  17.  
  18. // Callback function for receiving messages
  19. const receiveMessageCallback = async (msg) => {
  20. const message = msg.content.toString();
  21. const seconds = parseInt(message);
  22.  
  23. // Countdown from the received number of seconds
  24. countdown(seconds);
  25.  
  26. console.log(`Received number: ${seconds}`);
  27. channel.ack(msg);
  28. };
  29.  
  30. // Start consuming messages from the queue
  31. channel.consume(rabbitmqQueue, receiveMessageCallback, { noAck: false });
  32.  
  33. console.log('Waiting for messages...');
  34. } catch (error) {
  35. console.error('Error:', error);
  36. }
  37. }
  38.  
  39. function countdown(seconds) {
  40. for (let i = seconds; i > 0; i--) {
  41. console.log(`Countdown: ${i} seconds`);
  42. sleepSync(1000);
  43. }
  44. }
  45.  
  46. function sleepSync(ms) {
  47. const startTime = new Date().getTime();
  48. while (new Date().getTime() - startTime < ms) {}
  49. }
  50.  
  51. // Start the script
  52. connect();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement