time.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. "github.com/benbjohnson/clock"
  17. "time"
  18. )
  19. var (
  20. Clock clock.Clock
  21. )
  22. func InitClock() {
  23. if IsTesting {
  24. Log.Debugf("running in testing mode")
  25. Clock = clock.NewMock()
  26. } else {
  27. Clock = clock.New()
  28. }
  29. }
  30. func GetLocalZone() int {
  31. if IsTesting {
  32. return 28800 // default to UTC+8
  33. } else {
  34. _, offset := time.Now().Local().Zone()
  35. return offset
  36. }
  37. }
  38. //Time related. For Mock
  39. func GetTicker(duration int) *clock.Ticker {
  40. return Clock.Ticker(time.Duration(duration) * time.Millisecond)
  41. }
  42. func GetTimer(duration int) *clock.Timer {
  43. return Clock.Timer(time.Duration(duration) * time.Millisecond)
  44. }
  45. func GetTimerByTime(t time.Time) *clock.Timer {
  46. if IsTesting {
  47. return Clock.Timer(time.Duration(t.UnixMilli()-GetNowInMilli()) * time.Millisecond)
  48. } else {
  49. return Clock.Timer(time.Until(t))
  50. }
  51. }
  52. func GetNowInMilli() int64 {
  53. return Clock.Now().UnixMilli()
  54. }
  55. func GetNow() time.Time {
  56. return Clock.Now()
  57. }