fork(1) download
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "time"
  6. "os"
  7. "os/signal"
  8. )
  9.  
  10. type Timer struct {
  11. Queue chan *TimeCall
  12. }
  13.  
  14. func NewTimer(l int) *Timer {
  15. timer := new(Timer)
  16. timer.Queue = make(chan *TimeCall,l)
  17. return timer
  18. }
  19.  
  20. type TimeCall struct {
  21. timer *time.Timer
  22. callback func()
  23. }
  24.  
  25. func (this *TimeCall) CallBack() {
  26. defer func() { recover() }()
  27. if this.callback != nil {
  28. this.callback()
  29. }
  30. }
  31.  
  32. func (this *Timer) AfterFunc(d time.Duration, callback func()) *TimeCall {
  33. call := new(TimeCall)
  34. call.callback = callback
  35. call.timer = time.AfterFunc(d, func() {
  36. this.Queue <- call
  37. })
  38. return call
  39. }
  40.  
  41.  
  42.  
  43. type PipeService struct {
  44. TimeCall *Timer
  45. }
  46.  
  47. func (this *PipeService) AfterFunc(delay time.Duration, callback func()) *TimeCall {
  48. return this.TimeCall.AfterFunc(delay, callback)
  49. }
  50.  
  51. func (this *PipeService) IntervalCall(interval time.Duration, callback func()) {
  52. this.TimeCall.AfterFunc(interval,func(){
  53. if callback != nil {
  54. callback()
  55. }
  56. this.AfterFunc(interval,callback)
  57. })
  58. }
  59.  
  60. func (this *PipeService) Run(closeSig chan bool) {
  61. for {
  62. select {
  63. case <-closeSig:
  64. return
  65. case call := <-this.TimeCall.Queue:
  66. call.CallBack()
  67. }
  68. }
  69. }
  70.  
  71. func main() {
  72. var closeChan chan bool
  73. InsPipeService := &PipeService{TimeCall: NewTimer(10)}
  74. InsPipeService.IntervalCall(2*time.Second,func(){
  75. fmt.Println("interval call")
  76. })
  77.  
  78. c := make(chan os.Signal, 1)
  79. signal.Notify(c, os.Interrupt, os.Kill)
  80.  
  81. go func(){
  82. InsPipeService.Run(closeChan)
  83. }()
  84.  
  85. time.Sleep(10*time.Second)
  86. }
  87.  
Success #stdin #stdout 0s 790016KB
stdin
Standard input is empty
stdout
interval call
interval call