go.mway.dev/chrono@v0.6.1-0.20240126030049-189c5aef20d2/clock/ticker.go (about) 1 // Copyright (c) 2023 Matt Way 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to 5 // deal in the Software without restriction, including without limitation the 6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7 // sell copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 19 // IN THE THE SOFTWARE. 20 21 package clock 22 23 import ( 24 "errors" 25 "time" 26 ) 27 28 // A Ticker is functionally equivalent to a [time.Ticker]. A Ticker must be 29 // created by [Clock.NewTicker]. 30 type Ticker struct { 31 C <-chan time.Time 32 ticker *time.Ticker 33 fake *fakeTimer 34 } 35 36 // Reset stops a ticker and resets its period to the specified duration. The 37 // next tick will arrive after the new period elapses. The duration d must be 38 // greater than zero; if not, Reset will panic. 39 func (t *Ticker) Reset(d time.Duration) { 40 if t.ticker != nil { 41 t.ticker.Reset(d) 42 return 43 } 44 45 if d <= 0 { 46 panic(errors.New("non-positive interval for Ticker.Reset")) 47 } 48 49 t.fake.resetTimer(d) 50 } 51 52 // Stop turns off a ticker. After Stop, no more ticks will be sent. Stop does 53 // not close the channel, to prevent a concurrent goroutine reading from the 54 // channel from seeing an erroneous "tick". 55 func (t *Ticker) Stop() { 56 if t.ticker != nil { 57 t.ticker.Stop() 58 return 59 } 60 61 t.fake.removeTimer() 62 }