github.com/core-coin/go-core/v2@v2.1.9/les/utils/timeutils.go (about) 1 // Copyright 2020 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-core library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package utils 18 19 import ( 20 "sync" 21 "time" 22 23 "github.com/core-coin/go-core/v2/common/mclock" 24 ) 25 26 type UpdateTimer struct { 27 clock mclock.Clock 28 lock sync.Mutex 29 last mclock.AbsTime 30 threshold time.Duration 31 } 32 33 func NewUpdateTimer(clock mclock.Clock, threshold time.Duration) *UpdateTimer { 34 // We don't accept the update threshold less than 0. 35 if threshold < 0 { 36 return nil 37 } 38 // Don't panic for lazy users 39 if clock == nil { 40 clock = mclock.System{} 41 } 42 return &UpdateTimer{ 43 clock: clock, 44 last: clock.Now(), 45 threshold: threshold, 46 } 47 } 48 49 func (t *UpdateTimer) Update(callback func(diff time.Duration) bool) bool { 50 return t.UpdateAt(t.clock.Now(), callback) 51 } 52 53 func (t *UpdateTimer) UpdateAt(at mclock.AbsTime, callback func(diff time.Duration) bool) bool { 54 t.lock.Lock() 55 defer t.lock.Unlock() 56 57 diff := time.Duration(at - t.last) 58 if diff < 0 { 59 diff = 0 60 } 61 if diff < t.threshold { 62 return false 63 } 64 if callback(diff) { 65 t.last = at 66 return true 67 } 68 return false 69 }