common.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package ctrl_v1
  4. import (
  5. "gd_gateway/errors"
  6. "sync"
  7. "time"
  8. )
  9. const (
  10. NoLock = 0
  11. DataLock = 1
  12. TimeLock = 2
  13. )
  14. type Result struct {
  15. Chan chan error
  16. Data string
  17. Mutex sync.Mutex
  18. Flag int
  19. StartTime int64
  20. MinimalTimeConsuming int
  21. }
  22. func NewResult(startTime int64, minimalTimeConsuming int) Result {
  23. result := Result{}
  24. result.Chan = make(chan error, 1)
  25. result.Flag = NoLock
  26. result.StartTime = startTime / 1e9
  27. result.MinimalTimeConsuming = minimalTimeConsuming
  28. return result
  29. }
  30. func CheckDataLock(result *Result) bool {
  31. result.Mutex.Lock()
  32. defer result.Mutex.Unlock()
  33. // 数据业务处理持锁已处理
  34. if result.Flag == DataLock {
  35. return true
  36. } else {
  37. result.Flag = TimeLock
  38. return false
  39. }
  40. }
  41. // 如果已被定时任务处理
  42. func CheckTimeLock(result *Result) bool {
  43. result.Mutex.Lock()
  44. defer result.Mutex.Unlock()
  45. defer CheckMinimalTime(result)
  46. // 定时任务处理持锁已处理,接口已返回
  47. if result.Flag == TimeLock {
  48. return true
  49. } else {
  50. result.Flag = DataLock
  51. return false
  52. }
  53. }
  54. func CheckMinimalTime(result *Result) {
  55. //fmt.Printf("%+v", result)
  56. if result.MinimalTimeConsuming > 0 {
  57. useTime := int(time.Now().Unix() - result.StartTime)
  58. if useTime < result.MinimalTimeConsuming {
  59. time.Sleep(time.Duration(result.MinimalTimeConsuming-useTime) * time.Second)
  60. }
  61. }
  62. }
  63. // 获取结果
  64. func GetResult(timeOut int64, result *Result) (string, error) {
  65. defer close(result.Chan)
  66. if timeOut == 0 {
  67. for {
  68. select {
  69. case err := <-result.Chan:
  70. if err != nil {
  71. return "", err
  72. } else {
  73. return result.Data, nil
  74. }
  75. }
  76. }
  77. } else {
  78. after := time.After(time.Duration(timeOut) * time.Millisecond)
  79. //after := time.After(time.Duration(timeOut) * time.Second)
  80. for {
  81. select {
  82. case err := <-result.Chan:
  83. if err != nil {
  84. return "", err
  85. } else {
  86. return result.Data, nil
  87. }
  88. case <-after:
  89. if CheckDataLock(result) {
  90. err := <-result.Chan
  91. if err != nil {
  92. return "", err
  93. } else {
  94. return result.Data, nil
  95. }
  96. } else {
  97. return "", errors.NoRecord
  98. }
  99. }
  100. }
  101. }
  102. }