global_wait_group.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. return
  68. case <-time.After(time.Second * time.Duration(diff)):
  69. fmt.Println("全局waitgroup,超时结束")
  70. return
  71. }
  72. }
  73. func (this *globalWaitGroup) wait() {
  74. this.wg.Wait()
  75. this.ok <- true
  76. }
  77. func (this *globalWaitGroup) Done() {
  78. this.wg.Done()
  79. }
  80. func (this *globalWaitGroup) SetTimeout(timeout time.Time) {
  81. if timeout.Unix() <= 0 {
  82. return
  83. }
  84. this.lock.Lock()
  85. if this.timeout < timeout.Unix() {
  86. this.timeout = timeout.Unix()
  87. }
  88. this.lock.Unlock()
  89. }
  90. func (this *globalWaitGroup) Add(delta int) bool {
  91. if this.isStop {
  92. fmt.Println("已结束,不能在添加任务")
  93. return false
  94. }
  95. this.wg.Add(delta)
  96. return true
  97. }