Go study notes - timer, dot

Go study notes - timer, dot

1. Timer

The function of a timer timeris to make a piece of Go code run once after a specified period of time.

// The Timer type represents a single event.
// When the Timer expires, the current time will be sent on C,
// unless the Timer was created by AfterFunc.
// A Timer must be created with NewTimer or AfterFunc.
type Timer struct {
    
    
	C <-chan Time
	r runtimeTimer
}
  • A timer type represents a single event.
  • When the timer expires, the current time will be returned through channel C, unless the timer is AfterFunccreated by
  • You must use NewTimeror AfterFunccreate a timer

NewTimerCreates a timer that sends the current time on the channel after at least one duration.

The method of use is as follows:

timer := time.NewTimer(time.Second * 4)
//用变量接收一个传入时间值的方法产生的对象

The source code is as follows:

// NewTimer creates a new Timer that will send
// the current time on its channel after at least duration d.
func NewTimer(d Duration) *Timer {
    
    
	c := make(chan Time, 1)
	t := &Timer{
    
    
		C: c,
		r: runtimeTimer{
    
    
			when: when(d),
			f:    sendTime,
			arg:  c,
		},
	}
	startTimer(&t.r)
	return t
}

AfterFuncgoroutineWaits for the duration to elapse before calling it in its own f, freturning a timer that can be called with Stop()method cancel.

// AfterFunc waits for the duration to elapse and then calls f
// in its own goroutine. It returns a Timer that can
// be used to cancel the call using its Stop method.
func AfterFunc(d Duration, f func()) *Timer {
    
    
	t := &Timer{
    
    
		r: runtimeTimer{
    
    
			when: when(d),
			f:    goFunc,
			arg:  f,
		},
	}
	startTimer(&t.r)
	return t
}

//f 是一个函数类型,调用时传入goFunc
func goFunc(arg interface{
    
    }, seq uintptr) {
    
    
	go arg.(func())()
}

A timer refers to an independent event at a certain moment after a duration of time. will be sensed through a channel. Until the channel receives an invalidation message, it will remain blocked.

func main(){
    
    
    timer1 := time.NewTimer(time.Second * 4) //创建一个4秒后失效的定时器
    
    <- timer1.C //用于感知的通道
    fmt.Println("Timer 1 expired") //输出提示信息
}

//控制台四秒后输出信息
//Timer 1 expired

Unlike using time.Sleepto wait for an event to occur, a timer can be canceled before it expires.

func main(){
    
    
    timer2 := time.NewTimer(time.Second * 4)
    go func(){
    
    
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()

    stop2 := time2.Stop()
    if stop2 {
    
    
        fmt.Println("Timer 2 stopped")
    }
}

//控制台立即输出
//Timer 2 stopped

In this example, if no coroutine is used to control timer2the receipt of invalidation information, the console will wait for 4 seconds for output Timer 2 expired.

2. Dotting device

A ticker tickeris a program that repeats at a fixed interval until stopped.

// A Ticker holds a channel that delivers ``ticks'' of a clock
// at intervals.
type Ticker struct {
    
    
	C <-chan Time // The channel on which the ticks are delivered.
	r runtimeTimer
}

NewTickerCreate an inker, which will be executed periodically. NewTickerThe method of use is as follows:

ticker := time.NewTicker(time.Second * 1)
//用变量接收一个传入时间值的方法产生的对象

The source code is as follows:

// NewTicker returns a new Ticker containing a channel that will send
// the time on the channel after each tick. The period of the ticks is
// specified by the duration argument. The ticker will adjust the time
// interval or drop ticks to make up for slow receivers.
// The duration d must be greater than zero; if not, NewTicker will
// panic. Stop the ticker to release associated resources.
func NewTicker(d Duration) *Ticker {
    
    
	if d <= 0 {
    
    
		panic(errors.New("non-positive interval for NewTicker"))
	}
	// Give the channel a 1-element time buffer.
	// If the client falls behind while reading, we drop ticks
	// on the floor until the client catches up.
	c := make(chan Time, 1)
	t := &Ticker{
    
    
		C: c,
		r: runtimeTimer{
    
    
			when:   when(d),
			period: int64(d),
			f:      sendTime,
			arg:    c,
		},
	}
	startTimer(&t.r)
	return t
}
  • NewTickerReturns a ticker, containing a channel that sends the time of each tick.
  • The ticking time tickeris determined by the parameters passed in during generation.
  • The inker will adjust the time or reduce the number of dots to compensate for the slow acceptance.
  • The received time parameter must be greater than 0, otherwise an error message will be returned.
  • After use, close the inker tickerto save resources.

Create an object, perform a dot operation at intervals of 1 second, and return the dot time.

func main(){
    
    
    ticker := time.NewTicker(time.Second * 1)
    
    go func(){
    
    
        for t := range ticker.C{
    
      //从通道中获取时间值
            fmt.Println("Tick at",t)
        }
    }()
    
    time.Sleep(time.second * 3) //模拟函数程序时间
    ticker.Stop()
    fmt.Println("Ticker stopped")
}

//每间隔一秒,输出一条结果
//Tick at 2021-08-16 15:47:48.9317032 +0800 CST m=+1.002859901
//Tick at 2021-08-16 15:47:49.9427927 +0800 CST m=+2.013949401
//Ticker stopped

Guess you like

Origin blog.csdn.net/weixin_46435420/article/details/119735240