time.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2021-2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package conf
  15. import (
  16. "time"
  17. "github.com/benbjohnson/clock"
  18. )
  19. var Clock clock.Clock
  20. func InitClock() {
  21. if IsTesting {
  22. Log.Debugf("running in testing mode")
  23. Clock = clock.NewMock()
  24. } else {
  25. Clock = clock.New()
  26. }
  27. }
  28. func GetLocalZone() int {
  29. if IsTesting {
  30. return 28800 // default to UTC+8
  31. } else {
  32. _, offset := time.Now().Local().Zone()
  33. return offset
  34. }
  35. }
  36. // Time related. For Mock
  37. func GetTicker(duration int) *clock.Ticker {
  38. return Clock.Ticker(time.Duration(duration) * time.Millisecond)
  39. }
  40. func GetTimer(duration int) *clock.Timer {
  41. return Clock.Timer(time.Duration(duration) * time.Millisecond)
  42. }
  43. func GetTimerByTime(t time.Time) *clock.Timer {
  44. if IsTesting {
  45. return Clock.Timer(time.Duration(t.UnixMilli()-GetNowInMilli()) * time.Millisecond)
  46. } else {
  47. return Clock.Timer(time.Until(t))
  48. }
  49. }
  50. func GetNowInMilli() int64 {
  51. return Clock.Now().UnixMilli()
  52. }
  53. func GetNow() time.Time {
  54. return Clock.Now()
  55. }