Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Coroutine that regularly checks a heapify queue for messages to send?

Goal: A heapify priority queue that is regularly polled for message objects to send. Whenever the queue is polled, it should peek at the queue to see if there's any messages. If so, it should attempt to send the message.

On success, remove that message from the queue.

I'm worried about dropped messages, so if the message fails then it should remain in the queue to be sent on the next invocation. And the user will need to be alerted (but I will handle that part myself).

What I have so far:

        import { Heap } from 'heap-js';

        function coroutine(f) {
          var o = f(); // instantiate the coroutine
          o.next(); // execute until the first yield
          return function(x) {
            o.next(x);
          };
        }

        socket.messageQueue = new Heap(100);

        var messageBox = coroutine(async function*() {
            while (true) {
                yield;
                if (typeof socket.messageQueue.peek() === 'undefined') {
                    continue;
                }

                let message = socket.messageQueue.peek();
                let response = await sendMessage(socket, message);
                if (response.success) {
                    socket.messageQueue.pop();
                    // the message was sent
                    // reset warnings if they exist
                } else {
                    // warn user that the message send failed
                    // it will retry in 3 seconds
                }
            }
        });
        socket.messageBox = setInterval(messageBox, 3000);

And messages are added to the queue like so:

let priority = // the largest priority + 1
socket.messageQueue.push(message, priority);

The socket is from socket.io. I'm instantiating the process on a server-side socket because I'm going to tear it down when the user disconnects. And the queue is FIFO so the priority should just be set to the last priority. Unfortunately it doesn't look like heapify has a built-in method to get the largest priority from a heap.

Any suggestions on making this efficient and eloquent would be appreciated.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!