Documentation
¶
Index ¶
- type Config
- type Scheduler
- func (s *Scheduler) Cancel(taskID string) bool
- func (s *Scheduler) Schedule(delay time.Duration, fn func()) string
- func (s *Scheduler) SchedulePeriodic(interval time.Duration, fn func()) string
- func (s *Scheduler) SchedulePeriodicWithID(id string, interval time.Duration, fn func()) string
- func (s *Scheduler) ScheduleWithID(id string, delay time.Duration, fn func()) string
- func (s *Scheduler) Start()
- func (s *Scheduler) Stats() Stats
- func (s *Scheduler) Stop()
- type SkipList
- func (sl *SkipList) DeleteByID(taskID string) *Task
- func (sl *SkipList) Insert(task *Task)
- func (sl *SkipList) LazyDeleteByID(taskID string) *Task
- func (sl *SkipList) Len() int
- func (sl *SkipList) PeekMin() *Task
- func (sl *SkipList) PopMin() *Task
- func (sl *SkipList) PopMinBeforeOrEqual(threshold int64) *Task
- type SkipListNode
- type SparseWheel
- func (sw *SparseWheel) BucketsCount() int
- func (sw *SparseWheel) Cancel(taskID string) *Task
- func (sw *SparseWheel) Delete(taskID string) bool
- func (sw *SparseWheel) DeleteTask(taskID string) *Task
- func (sw *SparseWheel) Get(tick int64) map[string]*Task
- func (sw *SparseWheel) Insert(tick int64, task *Task)
- func (sw *SparseWheel) Len() int
- func (sw *SparseWheel) PeekNextTick() (int64, bool)
- func (sw *SparseWheel) PopTick(tick int64) []*Task
- func (sw *SparseWheel) PopTicksUpTo(maxTick int64) []*Task
- type Stats
- type Task
- type TicklessEngine
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
TickInterval time.Duration // 近期轮精度,默认 1ms
NearTermThreshold time.Duration // 近期/远期分界线,默认 60s
MigrationBatchSize int // 每次迁移的最大任务数,默认 128
LazyDeleteEnabled bool // 是否启用惰性删除,默认 true
}
Config 调度器配置
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler 自适应混合定时调度器
Example ¶
package main
import (
"fmt"
"time"
"github.com/atlaschan0010/timewheel"
)
func main() {
// 创建调度器
cfg := timewheel.DefaultConfig()
cfg.TickInterval = 10 * time.Millisecond // 加快示例速度
scheduler := timewheel.New(cfg)
// 启动调度器
scheduler.Start()
defer scheduler.Stop()
// 示例 1: 延迟任务
done := make(chan struct{})
scheduler.Schedule(100*time.Millisecond, func() {
fmt.Println("Delayed task executed!")
close(done)
})
<-done
}
Output: Delayed task executed!
Example (Cancel) ¶
package main
import (
"fmt"
"time"
"github.com/atlaschan0010/timewheel"
)
func main() {
cfg := timewheel.DefaultConfig()
cfg.TickInterval = 10 * time.Millisecond
scheduler := timewheel.New(cfg)
scheduler.Start()
defer scheduler.Stop()
executed := false
taskID := scheduler.Schedule(100*time.Millisecond, func() {
executed = true
fmt.Println("This should not print!")
})
// 取消任务
if scheduler.Cancel(taskID) {
fmt.Println("Task cancelled successfully")
}
time.Sleep(200 * time.Millisecond)
if !executed {
fmt.Println("Task was not executed (as expected)")
}
}
Output: Task cancelled successfully Task was not executed (as expected)
Example (Periodic) ¶
package main
import (
"fmt"
"sync/atomic"
"time"
"github.com/atlaschan0010/timewheel"
)
func main() {
cfg := timewheel.DefaultConfig()
cfg.TickInterval = 10 * time.Millisecond
scheduler := timewheel.New(cfg)
scheduler.Start()
defer scheduler.Stop()
var count atomic.Int32
tickerID := scheduler.SchedulePeriodic(50*time.Millisecond, func() {
c := count.Add(1)
fmt.Printf("Tick %d\n", c)
})
time.Sleep(180 * time.Millisecond)
scheduler.Cancel(tickerID)
fmt.Println("Ticker stopped")
}
Output: Tick 1 Tick 2 Tick 3 Ticker stopped
Example (Stats) ¶
package main
import (
"fmt"
"time"
"github.com/atlaschan0010/timewheel"
)
func main() {
cfg := timewheel.DefaultConfig()
cfg.TickInterval = 10 * time.Millisecond
scheduler := timewheel.New(cfg)
scheduler.Start()
defer scheduler.Stop()
// 调度多个任务
for i := 0; i < 5; i++ {
scheduler.Schedule(50*time.Millisecond, func() {})
}
// 调度一个远期任务(超过 60s 阈值,默认在远期结构)
scheduler.Schedule(70*time.Second, func() {})
time.Sleep(150 * time.Millisecond)
stats := scheduler.Stats()
fmt.Printf("Executed: %d\n", stats.TasksExecuted)
fmt.Printf("Near-term tasks: %d\n", stats.NearTermTasks)
fmt.Printf("Far-term tasks: %d\n", stats.FarTermTasks)
}
Output: Executed: 5 Near-term tasks: 0 Far-term tasks: 1
Example (WithID) ¶
package main
import (
"fmt"
"time"
"github.com/atlaschan0010/timewheel"
)
func main() {
cfg := timewheel.DefaultConfig()
cfg.TickInterval = 10 * time.Millisecond
scheduler := timewheel.New(cfg)
scheduler.Start()
defer scheduler.Stop()
done := make(chan struct{})
// 使用自定义 ID
scheduler.ScheduleWithID("my-task-1", 200*time.Millisecond, func() {
fmt.Println("This should NOT print (replaced)")
})
// 更新同名任务(会替换旧任务)
scheduler.ScheduleWithID("my-task-1", 100*time.Millisecond, func() {
fmt.Println("Task 1 (updated) executed!")
close(done)
})
<-done
}
Output: Task 1 (updated) executed!
func (*Scheduler) SchedulePeriodic ¶
SchedulePeriodic 调度周期任务
func (*Scheduler) SchedulePeriodicWithID ¶
SchedulePeriodicWithID 使用指定 ID 调度周期任务
func (*Scheduler) ScheduleWithID ¶
ScheduleWithID 使用指定 ID 调度延迟任务 如果 ID 已存在,旧任务会被取消并替换为新任务
type SkipList ¶
type SkipList struct {
// contains filtered or unexported fields
}
SkipList 跳表实现(按 ExpireAt 排序)
func (*SkipList) DeleteByID ¶
DeleteByID 根据任务 ID 删除任务
func (*SkipList) LazyDeleteByID ¶
LazyDeleteByID 根据任务 ID 惰性删除任务,仅移除索引并标记取消。
func (*SkipList) PopMinBeforeOrEqual ¶
PopMinBeforeOrEqual 原子弹出 ExpireAt <= threshold 的最小未取消任务。
type SkipListNode ¶
type SkipListNode struct {
// contains filtered or unexported fields
}
SkipListNode 跳表节点
type SparseWheel ¶
type SparseWheel struct {
// contains filtered or unexported fields
}
SparseWheel 稀疏时间轮
func (*SparseWheel) BucketsCount ¶
func (sw *SparseWheel) BucketsCount() int
BucketsCount 返回 bucket 数量
func (*SparseWheel) Cancel ¶
func (sw *SparseWheel) Cancel(taskID string) *Task
Cancel 惰性取消任务:移除反向索引,但保留 bucket 中的任务直到到期弹出。
func (*SparseWheel) Delete ¶
func (sw *SparseWheel) Delete(taskID string) bool
Delete 从时间轮中删除任务 — O(1) 通过反向索引
func (*SparseWheel) DeleteTask ¶
func (sw *SparseWheel) DeleteTask(taskID string) *Task
DeleteTask 从时间轮中物理删除任务 — O(1) 通过反向索引
func (*SparseWheel) Get ¶
func (sw *SparseWheel) Get(tick int64) map[string]*Task
Get 获取指定 tick 的 bucket(不删除)
func (*SparseWheel) Insert ¶
func (sw *SparseWheel) Insert(tick int64, task *Task)
Insert 插入任务到指定 tick
func (*SparseWheel) PeekNextTick ¶
func (sw *SparseWheel) PeekNextTick() (int64, bool)
PeekNextTick 查看下一个有任务的 tick — O(1) 通过最小堆 返回 tick 和是否存在
func (*SparseWheel) PopTick ¶
func (sw *SparseWheel) PopTick(tick int64) []*Task
PopTick 弹出指定 tick 的所有任务并从时间轮移除
func (*SparseWheel) PopTicksUpTo ¶
func (sw *SparseWheel) PopTicksUpTo(maxTick int64) []*Task
PopTicksUpTo 弹出所有 <= maxTick 的任务(处理漏掉的 tick)
type Stats ¶
type Stats struct {
TasksExecuted uint64
TasksCancelled uint64
TasksMigrated uint64
NearTermTasks int
FarTermTasks int
}
Stats 统计信息
type Task ¶
type Task struct {
ID string
ExpireAt int64 // 到期时间戳(毫秒)
Interval int64 // 周期任务间隔(毫秒),0 表示非周期
Cancelled atomic.Bool // 取消标记(惰性删除)
Fn func() // 任务函数
// contains filtered or unexported fields
}
Task 定时任务
type TicklessEngine ¶
type TicklessEngine struct {
// contains filtered or unexported fields
}
TicklessEngine 无空转唤醒引擎
func NewTicklessEngine ¶
func NewTicklessEngine(scheduler *Scheduler) *TicklessEngine
NewTicklessEngine 创建新的无空转唤醒引擎
func (*TicklessEngine) CalculateNextWakeTime ¶
func (te *TicklessEngine) CalculateNextWakeTime() int64
CalculateNextWakeTime 计算下一次唤醒时间 返回毫秒时间戳,0 表示无任务
func (*TicklessEngine) NotifyIfEarlier ¶
func (te *TicklessEngine) NotifyIfEarlier(expireAt int64)
NotifyIfEarlier 如果新的到期时间早于当前最早时间,唤醒引擎
func (*TicklessEngine) ResetEarliestExpire ¶
func (te *TicklessEngine) ResetEarliestExpire()
ResetEarliestExpire 重置最早到期时间 在任务被执行或取消后调用
func (*TicklessEngine) SleepUntil ¶
func (te *TicklessEngine) SleepUntil(targetTime int64) bool
SleepUntil 睡眠直到指定时间(或直到被唤醒或 context 取消) 返回 true 表示正常超时,false 表示被提前唤醒或取消
func (*TicklessEngine) WaitForTask ¶
func (te *TicklessEngine) WaitForTask() bool
WaitForTask 等待直到有任务可执行(无任务时阻塞) 返回 false 表示 context 已取消