Skip to content

Commit a235753

Browse files
committed
简单的时间轮定时任务
1 parent 8405150 commit a235753

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

timewheel/timewheel.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,11 @@ func (t *TimeWheel) runTask() {
171171
t.currentSlots++
172172
}
173173
}
174+
175+
func (t *TimeWheel) getInitSlots() int64 {
176+
return time.Now().Unix() % t.slotsNum
177+
}
178+
174179
func (t *TimeWheel) getCircleAndSlots(delay time.Duration, first bool) (circle, slots int64) {
175180
delaySed := int64(delay.Seconds())
176181
intervalSed := int64(t.interval.Seconds())
@@ -179,6 +184,8 @@ func (t *TimeWheel) getCircleAndSlots(delay time.Duration, first bool) (circle,
179184
if slots == t.currentSlots && circle > 0 {
180185
circle--
181186
}
187+
//第一次加入时 当前秒(currentSlots)还未执行,比如当前是第一秒的slot(0) 延迟5秒计算得出为5 (0~5有6格所有需要-1)
188+
//第二次加入时 当前秒(currentSlots)已经执行,就不需要-1
182189
if slots > 0 && first {
183190
slots--
184191
}

timewheel/timewheel_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,9 @@ import (
88

99
func TestAddTask(t *testing.T) {
1010
tw := DefaultTimeWheel()
11-
time.Sleep(5 * time.Second)
1211
err := tw.AddTask("task-1", func(key string) {
1312
fmt.Println("task run :", key, " > ", time.Now().Format(time.DateTime))
14-
}, 2*time.Second, 6)
13+
}, 3*time.Second, 6)
1514
t.Log("err", err)
1615
//time.Sleep(time.Second * 3)
1716
//tw.Stop()

0 commit comments

Comments
 (0)