← 中文资源

简体中文版本

用 container/heap 按截止时间调度重试

基于 container/heap 按最早触发时间与任务 ID 排列重试队列,依次弹出到期任务并将退避后的新尝试重新入堆。

阅读英文原文

实现说明

核心业务逻辑均落在函数体中: Len、Less、Swap、Push,其余都是接线。 迭代发生在 for q.Len() > 0 内部——循环之外的语句只执行一遍。

使用要点

  • 第三方依赖列表为空,全部调用由标准运行时满足。
  • 演示输出是带标签的(t=),每个操作都会留下自己的一行标注。
  • 运行整个文件:main 会依次驱动 Len、Pop、Push。

常见问题

运行「用 container/heap 按截止时间调度重试」会打印什么?

整个文件跑完,输出行以 t= 这类前缀开头。

主要签名是 func (h retryHeap) Len() int

核心语句

func (h *retryHeap) Push(x any)   { *h = append(*h, x.(RetryJob)) }
func (h retryHeap) Len() int { return len(h) }
func (h retryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }

代码示例

package main

import (
	"container/heap"
	"fmt"
)

type RetryJob struct {
	ID      string
	RunAtMs int
	Attempt int
}

type retryHeap []RetryJob

func (h retryHeap) Len() int { return len(h) }
func (h retryHeap) Less(i, j int) bool {
	if h[i].RunAtMs != h[j].RunAtMs {
		return h[i].RunAtMs < h[j].RunAtMs
	}
	return h[i].ID < h[j].ID
}
func (h retryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *retryHeap) Push(x any)   { *h = append(*h, x.(RetryJob)) }
func (h *retryHeap) Pop() any {
	old := *h
	item := old[len(old)-1]
	*h = old[:len(old)-1]
	return item
}

func main() {
	q := &retryHeap{
		{ID: "job-b", RunAtMs: 300, Attempt: 1},
		{ID: "job-a", RunAtMs: 100, Attempt: 1},
		{ID: "job-c", RunAtMs: 100, Attempt: 2},
	}
	heap.Init(q)

	for q.Len() > 0 {
		job := heap.Pop(q).(RetryJob)
		fmt.Printf("t=%dms run %s (attempt %d)\n", job.RunAtMs, job.ID, job.Attempt)
		if job.ID == "job-a" && job.Attempt == 1 {
			heap.Push(q, RetryJob{
				ID:      job.ID,
				RunAtMs: job.RunAtMs + 250,
				Attempt: job.Attempt + 1,
			})
		}
	}
}