github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/every_n.go (about) 1 // Copyright 2017 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package util 12 13 import ( 14 "time" 15 16 "github.com/cockroachdb/cockroachdb-parser/pkg/util/syncutil" 17 ) 18 19 // EveryN provides a way to rate limit spammy events. It tracks how recently a 20 // given event has occurred so that it can determine whether it's worth 21 // handling again. 22 // 23 // The zero value for EveryN is usable and is equivalent to Every(0), meaning 24 // that all calls to ShouldProcess will return true. 25 // 26 // NOTE: If you specifically care about log messages, you should use the 27 // version of this in the log package, as it integrates with the verbosity 28 // flags. 29 type EveryN struct { 30 // N is the minimum duration of time between log messages. 31 N time.Duration 32 33 syncutil.Mutex 34 lastProcessed time.Time 35 } 36 37 // Every is a convenience constructor for an EveryN object that allows a log 38 // message every n duration. 39 func Every(n time.Duration) EveryN { 40 return EveryN{N: n} 41 } 42 43 // ShouldProcess returns whether it's been more than N time since the last event. 44 func (e *EveryN) ShouldProcess(now time.Time) bool { 45 var shouldProcess bool 46 e.Lock() 47 if now.Sub(e.lastProcessed) >= e.N { 48 shouldProcess = true 49 e.lastProcessed = now 50 } 51 e.Unlock() 52 return shouldProcess 53 }