github.com/polarismesh/polaris@v1.17.8/service/healthcheck/time_adjust.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package healthcheck 19 20 import ( 21 "context" 22 "sync/atomic" 23 "time" 24 25 "github.com/polarismesh/polaris/store" 26 ) 27 28 const adjustInterval = 60 * time.Second 29 30 // TimeAdjuster adjust the seconds from databases 31 type TimeAdjuster struct { 32 diff int64 33 storage store.Store 34 } 35 36 func newTimeAdjuster(ctx context.Context, storage store.Store) *TimeAdjuster { 37 adjuster := &TimeAdjuster{storage: storage} 38 return adjuster 39 } 40 41 func (t *TimeAdjuster) doTimeAdjust(ctx context.Context) { 42 t.calcDiff() 43 ticker := time.NewTicker(adjustInterval) 44 defer ticker.Stop() 45 for { 46 select { 47 case <-ctx.Done(): 48 log.Infof("[Health Check] time adjuster has been stopped") 49 return 50 case <-ticker.C: 51 t.calcDiff() 52 } 53 } 54 } 55 56 func (t *TimeAdjuster) calcDiff() { 57 curTimeSecond, err := t.storage.GetUnixSecond(time.Second) 58 if err != nil { 59 log.Errorf("[Health Check] fail to get now from store, err is %s", err.Error()) 60 return 61 } 62 if curTimeSecond == 0 { 63 return 64 } 65 sysNow := time.Now().Unix() 66 diff := sysNow - curTimeSecond 67 if diff != 0 { 68 log.Infof("[Health Check] time diff from now is %d", diff) 69 } 70 atomic.StoreInt64(&t.diff, diff) 71 } 72 73 // GetDiff get diff time between store and current PC 74 func (t *TimeAdjuster) GetDiff() int64 { 75 if nil == t { 76 return 0 77 } 78 return atomic.LoadInt64(&t.diff) 79 }