global_wait_group.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package common
  2. /**
  3. import中必须有git.ikuban.com/server/kratos-utils/common
  4. import (
  5. "context"
  6. "fmt"
  7. "time"
  8. "git.ikuban.com/server/kratos-utils/common"
  9. )
  10. func main() {
  11. test()
  12. go test()
  13. common.GlobalWaitGroup.Stop()
  14. }
  15. func test() {
  16. ok := common.GlobalWaitGroup.Add(1)
  17. if !ok {
  18. return
  19. }
  20. common.GlobalWaitGroup.SetTimeout(time.Now().Unix() + 12)
  21. go func() {
  22. fmt.Println("任务开始")
  23. time.Sleep(time.Second * 11)
  24. fmt.Println("任务完成")
  25. common.GlobalWaitGroup.Done()
  26. }()
  27. }
  28. */
  29. import (
  30. "fmt"
  31. "sync"
  32. "time"
  33. )
  34. var GlobalWaitGroup *globalWaitGroup
  35. func init() {
  36. GlobalWaitGroup = NewGlobalWaitGroup()
  37. }
  38. type globalWaitGroup struct {
  39. wg sync.WaitGroup
  40. timeout int64 //超时时间, 时间戳
  41. isStop bool
  42. lock sync.Mutex
  43. ok chan bool
  44. }
  45. func NewGlobalWaitGroup() *globalWaitGroup {
  46. this := &globalWaitGroup{
  47. wg: sync.WaitGroup{},
  48. isStop: false,
  49. ok: make(chan bool, 1),
  50. }
  51. return this
  52. }
  53. func (this *globalWaitGroup) Stop() {
  54. this.isStop = true
  55. this.Wait()
  56. }
  57. func (this *globalWaitGroup) Wait() {
  58. go func() {
  59. this.wait()
  60. }()
  61. diff := this.timeout - time.Now().Unix()
  62. if diff <= 0 {
  63. diff = 10
  64. }
  65. select {
  66. case <-this.ok:
  67. fmt.Println("没有任务而结束")
  68. return
  69. case <-time.After(time.Second * time.Duration(diff)):
  70. fmt.Println("超时结束")
  71. return
  72. }
  73. }
  74. func (this *globalWaitGroup) wait() {
  75. this.wg.Wait()
  76. this.ok <- true
  77. }
  78. func (this *globalWaitGroup) Done() {
  79. this.wg.Done()
  80. }
  81. func (this *globalWaitGroup) SetTimeout(timeout int64) {
  82. if timeout <= 0 {
  83. return
  84. }
  85. this.lock.Lock()
  86. if this.timeout < timeout {
  87. this.timeout = timeout
  88. }
  89. this.lock.Unlock()
  90. }
  91. func (this *globalWaitGroup) Add(delta int) bool {
  92. if this.isStop {
  93. fmt.Println("已结束,不能在添加任务")
  94. return false
  95. }
  96. this.wg.Add(delta)
  97. return true
  98. }