package main
import (
"fmt"
"time"
"os"
"os/signal"
)
type Timer struct {
Queue chan *TimeCall
}
func NewTimer(l int) *Timer {
timer := new(Timer)
timer.Queue = make(chan *TimeCall,l)
return timer
}
type TimeCall struct {
callback func()
}
func (this *TimeCall) CallBack() {
defer func() { recover() }()
if this.callback != nil {
this.callback()
}
}
func
(this
*Timer
) AfterFunc
(d
time.
Duration, callback func
()) *TimeCall
{ call := new(TimeCall)
call.callback = callback
call.
timer = time.
AfterFunc(d
, func
() { this.Queue <- call
})
return call
}
type PipeService struct {
TimeCall *Timer
}
func
(this
*PipeService
) AfterFunc
(delay
time.
Duration, callback func
()) *TimeCall
{ return this.TimeCall.AfterFunc(delay, callback)
}
func
(this
*PipeService
) IntervalCall
(interval
time.
Duration, callback func
()) { this.TimeCall.AfterFunc(interval,func(){
if callback != nil {
callback()
}
this.AfterFunc(interval,callback)
})
}
func (this *PipeService) Run(closeSig chan bool) {
for {
select {
case <-closeSig:
return
case call := <-this.TimeCall.Queue:
call.CallBack()
}
}
}
func main() {
var closeChan chan bool
InsPipeService := &PipeService{TimeCall: NewTimer(10)}
InsPipeService.
IntervalCall(2*time.
Second,func
(){ fmt.Println("interval call")
})
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)
go func(){
InsPipeService.Run(closeChan)
}()
}
cGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKCSJ0aW1lIgoJIm9zIgoJIm9zL3NpZ25hbCIKKQoKdHlwZSBUaW1lciBzdHJ1Y3QgewoJUXVldWUgY2hhbiAqVGltZUNhbGwKfQoKZnVuYyBOZXdUaW1lcihsIGludCkgKlRpbWVyIHsKCXRpbWVyIDo9IG5ldyhUaW1lcikKCXRpbWVyLlF1ZXVlID0gbWFrZShjaGFuICpUaW1lQ2FsbCxsKQoJcmV0dXJuIHRpbWVyCn0KCnR5cGUgVGltZUNhbGwgc3RydWN0IHsKCXRpbWVyICAgICp0aW1lLlRpbWVyCgljYWxsYmFjayBmdW5jKC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