/
RunnaStyle.go
100 lines (83 loc) · 1.48 KB
/
RunnaStyle.go
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
96
97
98
99
100
package main
import (
"fmt"
"sync/atomic"
"time"
)
type Runnable func() bool // true: performed, false: not performed
type RunnaStyle struct {
RunInterval time.Duration
maxidle int32
sem int32
}
func (r *RunnaStyle) ShutDown() {
atomic.StoreInt32(&r.sem, -1)
}
func (r *RunnaStyle) Run(f Runnable) {
if atomic.CompareAndSwapInt32(&r.sem, 0, 1) {
go func() {
ticker := time.NewTicker(r.RunInterval)
defer ticker.Stop()
fmt.Println("let's run")
var idle int32 = 0
for {
if atomic.LoadInt32(&r.sem) == -1 {
return
}
<-ticker.C
if f() {
idle = 0
} else {
idle++
}
if idle >= r.maxidle {
fmt.Println("idle for", idle)
break
}
}
atomic.CompareAndSwapInt32(&r.sem, 1, 0)
}()
} else {
fmt.Println("already running")
}
}
// for test -----------------------------------------
type T struct {
count int32
msg string
r *RunnaStyle
}
func NewT() *T {
return &T{
r: &RunnaStyle{
RunInterval: 1 * time.Second,
maxidle: 4,
},
msg: "name--",
}
}
func (t *T) Run() {
t.r.Run(func() bool {
t.count++
fmt.Println("---", t.msg, t.count)
return true
})
}
func main() {
t := NewT()
time.AfterFunc(1*time.Second, func() {
t.Run()
})
time.AfterFunc(6*time.Second, func() {
t.Run()
})
c := make(chan (int))
time.AfterFunc(8*time.Second, func() {
t.r.ShutDown()
fmt.Println("ShutDown")
c <- 1
})
<-c
time.Sleep(300 * time.Nanosecond)
fmt.Println("game over")
}