-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.go
More file actions
95 lines (81 loc) · 1.64 KB
/
timer.go
File metadata and controls
95 lines (81 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2017 Granitic. All rights reserved.
// Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.
package timer
type Complete func(*Timer) int64
type Timer struct {
count int64
value int64
complete Complete
fn func()
next, prev *Timer
list *Slot
}
func toZero(*Timer) int64 {
return 0
}
func toValue(tm *Timer) int64 {
return tm.value
}
func makeToTable(tab []int64) Complete {
return func(tm *Timer) int64 {
if tm.value++; tm.value < int64(len(tab)) {
return tab[tm.value]
}
return 0
}
}
func makeToTimes(times int64, complete Complete) Complete {
return func(tm *Timer) int64 {
if times--; times > 0 {
return complete(tm)
}
return 0
}
}
func NewTimer(fn func(), count int64) *Timer {
return &Timer{
count: count,
value: count,
complete: toValue,
fn: fn,
}
}
func NewTimerTable(fn func(), count ...int64) *Timer {
if 1 == len(count){
return &Timer{
count: count[0],
complete: toZero,
fn: fn,
}
}
return &Timer{
count: count[0],
complete: makeToTable(count),
fn: fn,
}
}
func NewTimerPeriodic(fn func(), times, count int64) *Timer {
return &Timer{
count: count,
value: count,
complete: makeToTimes(times, toValue),
fn: fn,
}
}
func NewTimerCustom(fn func(), complete Complete, count int64) *Timer {
return &Timer{
count: count,
complete: complete,
fn: fn,
}
}
func (e *Timer) remove() *Timer {
if nil != e.list {
return e.list.Remove(e)
}
return nil
}
func (e *Timer) Cancel() {
e.fn = func() {}
e.complete = toZero
}