-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer.go
More file actions
50 lines (43 loc) · 726 Bytes
/
timer.go
File metadata and controls
50 lines (43 loc) · 726 Bytes
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
package gotimer
import (
"sync"
"time"
)
type Timer struct {
lock sync.Mutex
jobs map[string]*Job
}
func NewTimer() *Timer {
t := &Timer{
jobs: map[string]*Job{},
}
return t
}
func (t *Timer) Clear() {
t.lock.Lock()
defer t.lock.Unlock()
for _, job := range t.jobs {
job.stop()
}
clear(t.jobs)
}
func (t *Timer) AddFunc(duration time.Duration, cmd func()) string {
job := NewJob(duration)
t.saveTicker(job.id, job)
job.start(cmd)
return job.id
}
func (t *Timer) saveTicker(id string, job *Job) {
t.lock.Lock()
defer t.lock.Unlock()
t.jobs[id] = job
}
func (t *Timer) Remove(id string) {
t.lock.Lock()
defer t.lock.Unlock()
job, ok := t.jobs[id]
if ok {
job.stop()
delete(t.jobs, id)
}
}