github.com/dubbogo/gost@v1.14.0/time/ticker.go (about) 1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 // Package gxtime encapsulates some golang.time functions 19 package gxtime 20 21 import ( 22 "time" 23 ) 24 25 // Ticker is a wrapper of TimerWheel in golang Ticker style 26 type Ticker struct { 27 C <-chan time.Time 28 ID TimerID 29 w *TimerWheel 30 } 31 32 // NewTicker returns a new Ticker 33 func NewTicker(d time.Duration) *Ticker { 34 if d <= 0 { 35 return nil 36 } 37 38 return defaultTimerWheel.NewTicker(d) 39 } 40 41 // TickFunc returns a Ticker 42 func TickFunc(d time.Duration, f func()) *Ticker { 43 if d <= 0 { 44 return nil 45 } 46 47 return defaultTimerWheel.TickFunc(d, f) 48 } 49 50 // Tick is a convenience wrapper for NewTicker providing access to the ticking 51 // channel only. While Tick is useful for clients that have no need to shut down 52 // the Ticker, be aware that without a way to shut it down the underlying 53 // Ticker cannot be recovered by the garbage collector; it "leaks". 54 // Unlike NewTicker, Tick will return nil if d <= 0. 55 func Tick(d time.Duration) <-chan time.Time { 56 if d <= 0 { 57 return nil 58 } 59 60 return defaultTimerWheel.Tick(d) 61 } 62 63 // Stop turns off a ticker. After Stop, no more ticks will be sent. 64 // Stop does not close the channel, to prevent a concurrent goroutine 65 // reading from the channel from seeing an erroneous "tick". 66 func (t *Ticker) Stop() { 67 (*Timer)(t).Stop() 68 } 69 70 // Reset stops a ticker and resets its period to the specified duration. 71 // The next tick will arrive after the new period elapses. 72 func (t *Ticker) Reset(d time.Duration) { 73 if d <= 0 { 74 return 75 } 76 77 (*Timer)(t).Reset(d) 78 }