Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change Timer to TimerTask interface #52

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import (
"unsafe"
)

type TimerTask interface {
Stop() bool
}

// Timer represents a single event. When the Timer expires, the given
// task will be executed.
type Timer struct {
Expand Down
12 changes: 8 additions & 4 deletions timingwheel.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func (tw *TimingWheel) Stop() {

// AfterFunc waits for the duration to elapse and then calls f in its own goroutine.
// It returns a Timer that can be used to cancel the call using its Stop method.
func (tw *TimingWheel) AfterFunc(d time.Duration, f func()) *Timer {
func (tw *TimingWheel) AfterFunc(d time.Duration, f func()) TimerTask {
t := &Timer{
expiration: timeToMs(time.Now().UTC().Add(d)),
task: f,
Expand Down Expand Up @@ -199,11 +199,15 @@ type Scheduler interface {
// Afterwards, it will ask the next execution time each time f is about to
// be executed, and f will be called at the next execution time if the time
// is non-zero.
func (tw *TimingWheel) ScheduleFunc(s Scheduler, f func()) (t *Timer) {
func (tw *TimingWheel) ScheduleFunc(s Scheduler, f func()) TimerTask {
var (
t = new(Timer)
)

expiration := s.Next(time.Now().UTC())
if expiration.IsZero() {
// No time is scheduled, return nil.
return
return t
}

t = &Timer{
Expand All @@ -222,5 +226,5 @@ func (tw *TimingWheel) ScheduleFunc(s Scheduler, f func()) (t *Timer) {
}
tw.addOrRun(t)

return
return t
}
2 changes: 1 addition & 1 deletion timingwheel_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func BenchmarkTimingWheel_StartStop(b *testing.B) {
}
for _, c := range cases {
b.Run(c.name, func(b *testing.B) {
base := make([]*timingwheel.Timer, c.N)
base := make([]timingwheel.TimerTask, c.N)
for i := 0; i < len(base); i++ {
base[i] = tw.AfterFunc(genD(i), func() {})
}
Expand Down