How to Batch and Timeout Tasks with RabbitMQ in Node.js?

I’m working on a project that interacts with the blockchain using Node.js and RabbitMQ. I need to implement a system where tasks are batched into an array before being sent to the blockchain. The requirements are:

  1. Each worker should collect up to 5 tasks and combine them into an array and send the array to the blockchain.
  2. If a worker has fewer than 5 tasks but the first task has been waiting for at least 5 minutes, the worker should send the available tasks to the blockchain anyway (as an array of course).

I know I can write and handle the timeout or the tasks manually, but I was just wondering if there is a way to handle it purely using RabbitMQ workers.

I asked ChatGPT and here’s the answer, and the code handles everything itself, since I’m new to RabbitMQ, I wanted to know if there’s a better way to handle it.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const amqp = require('amqplib/callback_api');
const { sendToBlockchain } = require('./blockchain'); // Function to send tasks to the blockchain
const QUEUE = 'task_queue';
const MAX_TASKS = 5;
const MAX_WAIT_TIME = 5 * 60 * 1000; // 5 minutes in milliseconds
let taskBuffer = [];
let timer = null;
let firstTaskTime = null;
amqp.connect('amqp://localhost', function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
channel.assertQueue(QUEUE, {
durable: true
});
console.log("Waiting for messages in %s. To exit press CTRL+C", QUEUE);
channel.consume(QUEUE, function(msg) {
const task = msg.content.toString();
console.log("Received %s", task);
if (taskBuffer.length === 0) {
firstTaskTime = Date.now();
startTimer();
}
taskBuffer.push(task);
if (taskBuffer.length >= MAX_TASKS) {
processTasks();
}
}, {
noAck: true
});
});
});
function startTimer() {
timer = setTimeout(() => {
if (taskBuffer.length > 0) {
processTasks();
}
}, MAX_WAIT_TIME);
}
function processTasks() {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (taskBuffer.length > 0) {
sendToBlockchain(taskBuffer)
.then(() => {
console.log('Tasks sent to blockchain:', taskBuffer);
taskBuffer = [];
firstTaskTime = null;
})
.catch(error => {
console.error('Error sending tasks to blockchain:', error);
});
}
}
</code>
<code>const amqp = require('amqplib/callback_api'); const { sendToBlockchain } = require('./blockchain'); // Function to send tasks to the blockchain const QUEUE = 'task_queue'; const MAX_TASKS = 5; const MAX_WAIT_TIME = 5 * 60 * 1000; // 5 minutes in milliseconds let taskBuffer = []; let timer = null; let firstTaskTime = null; amqp.connect('amqp://localhost', function(error0, connection) { if (error0) { throw error0; } connection.createChannel(function(error1, channel) { if (error1) { throw error1; } channel.assertQueue(QUEUE, { durable: true }); console.log("Waiting for messages in %s. To exit press CTRL+C", QUEUE); channel.consume(QUEUE, function(msg) { const task = msg.content.toString(); console.log("Received %s", task); if (taskBuffer.length === 0) { firstTaskTime = Date.now(); startTimer(); } taskBuffer.push(task); if (taskBuffer.length >= MAX_TASKS) { processTasks(); } }, { noAck: true }); }); }); function startTimer() { timer = setTimeout(() => { if (taskBuffer.length > 0) { processTasks(); } }, MAX_WAIT_TIME); } function processTasks() { if (timer) { clearTimeout(timer); timer = null; } if (taskBuffer.length > 0) { sendToBlockchain(taskBuffer) .then(() => { console.log('Tasks sent to blockchain:', taskBuffer); taskBuffer = []; firstTaskTime = null; }) .catch(error => { console.error('Error sending tasks to blockchain:', error); }); } } </code>
const amqp = require('amqplib/callback_api');
const { sendToBlockchain } = require('./blockchain'); // Function to send tasks to the blockchain

const QUEUE = 'task_queue';
const MAX_TASKS = 5;
const MAX_WAIT_TIME = 5 * 60 * 1000; // 5 minutes in milliseconds

let taskBuffer = [];
let timer = null;
let firstTaskTime = null;

amqp.connect('amqp://localhost', function(error0, connection) {
  if (error0) {
    throw error0;
  }
  connection.createChannel(function(error1, channel) {
    if (error1) {
      throw error1;
    }
    channel.assertQueue(QUEUE, {
      durable: true
    });

    console.log("Waiting for messages in %s. To exit press CTRL+C", QUEUE);

    channel.consume(QUEUE, function(msg) {
      const task = msg.content.toString();
      console.log("Received %s", task);

      if (taskBuffer.length === 0) {
        firstTaskTime = Date.now();
        startTimer();
      }

      taskBuffer.push(task);

      if (taskBuffer.length >= MAX_TASKS) {
        processTasks();
      }
    }, {
      noAck: true
    });
  });
});

function startTimer() {
  timer = setTimeout(() => {
    if (taskBuffer.length > 0) {
      processTasks();
    }
  }, MAX_WAIT_TIME);
}

function processTasks() {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }

  if (taskBuffer.length > 0) {
    sendToBlockchain(taskBuffer)
      .then(() => {
        console.log('Tasks sent to blockchain:', taskBuffer);
        taskBuffer = [];
        firstTaskTime = null;
      })
      .catch(error => {
        console.error('Error sending tasks to blockchain:', error);
      });
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật