Member-only story

Efficient Delayed Task Scheduling in Go: From Simple Queues to Priority Queues

Beck Moulton
3 min readSep 7, 2023

--

Simple Go Language Delayed Queue Idea.


package main

import (
"fmt"
"time"
)

// Message is a structure that holds the contents of the message.
type Message struct {
ID int
Body string
Delay time.Duration
}

// delayMessageQueue holds the queue of messages
type delayMessageQueue struct {
queue []Message
}

func (d *delayMessageQueue) send(msg Message) {
go func() {
timer := time.NewTimer(msg.Delay)
<-timer.C
d.queue = append(d.queue, msg)
fmt.Printf("Message %d sent\n", msg.ID)
}()
}

func (d *delayMessageQueue) receive() {
for {
if len(d.queue) > 0 {
msg := d.queue[0]
fmt.Printf("Message %d received \n", msg.ID)
d.queue = d.queue[1:] // Dequeue
}
end
}

func main() {
dmq := &delayMessageQueue{}
dmq.send(Message{ID: 1, Body: "Hello, World", Delay: 2 * time.Second})
dmq.send(Message{ID: 2, Body: "Hello, Go", Delay: 1 * time.Second})

// Keep the main function alive to let goroutines finish
time.Sleep(5 * time.Second)

dmq.receive()
}

We’ve defined a Message structure containing an ID, message body, and delay. We also have a delayMessageQueue type with send and receive methods.

The send method puts messages into a goroutine and waits for the specified delay using a timer. When the timer expires, the message is added to the queue.

The receive method continuously checks the queue and prints the message content when there are…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet