You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
913 B
56 lines
913 B
package timer |
|
|
|
import ( |
|
"cmp" |
|
"sig-pub/pkg/utils/container" |
|
"sync" |
|
"sync/atomic" |
|
"time" |
|
) |
|
|
|
type timerTask struct { |
|
ExecuteAt int64 |
|
Canceled atomic.Bool |
|
Handler func() |
|
} |
|
|
|
// Timer todo 使用二叉树堆的定时任务执行器 |
|
type Timer[T any] struct { |
|
mu sync.RWMutex |
|
heap *container.Heap[T, int64] |
|
tick time.Duration |
|
ticker *time.Ticker |
|
} |
|
|
|
func NewTimer[T any, C cmp.Ordered](tick time.Duration, compare func(T) int64) *Timer[T] { |
|
return &Timer[T]{ |
|
heap: container.NewHeap(compare), |
|
tick: tick, |
|
} |
|
} |
|
|
|
func (t *Timer[T]) Init() { |
|
t.ticker = time.NewTicker(t.tick) |
|
go func() { |
|
for { |
|
now, ok := <-t.ticker.C |
|
if !ok { |
|
return |
|
} |
|
t.mu.RLock() |
|
v, ok := t.heap.Peek() |
|
t.mu.RUnlock() |
|
if !ok { |
|
continue |
|
} |
|
_, _ = now, v |
|
// todo handler |
|
} |
|
}() |
|
// time.Unix() |
|
// t.ticker.C |
|
} |
|
|
|
func (t *Timer[T]) Push(v T, duration time.Duration) { |
|
t.heap.Push(v) |
|
}
|
|
|