Home > Backend Development > Golang > What is the method to implement timer in go language

What is the method to implement timer in go language

王林
Release: 2023-01-13 00:21:43
Original
2516 people have browsed it

How to implement timers in go language: timers can be implemented through time.sleep, time.after and time.Timer, such as [time.Sleep(time.Second)].

What is the method to implement timer in go language

The operating environment of this article: windows10 system, Go 1.11.2, thinkpad t480 computer.

1. Creation of timer

There are three ways to implement timers in golang, namely time.sleep, time.after, time.Timer
Among them time.after and time. Timer needs to release the channel to achieve the timing effect

package mainimport (    "fmt"
    "time")func main() {    /*
        用sleep实现定时器
    */
    fmt.Println(time.Now())
    time.Sleep(time.Second)
    fmt.Println(time.Now())    /*
        用timer实现定时器
    */
    timer := time.NewTimer(time.Second)
    fmt.Println(<-timer.C)    /*
        用after实现定时器
    */
    fmt.Println(<-time.After(time.Second))

}
Copy after login

2. Reset and stop the timer

Reset the timer timer.Reset(d Duration)
Stop the timer timer.Stop()
3. Implementation of periodic timing Tiker

Using Tiker in golang can achieve the effect of periodic timing

package main

import (    "fmt"
    "time")

func main() {
    tiker := time.NewTicker(time.Second)    for i := 0; i < 3; i++ {
        fmt.Println(<-tiker.C)
    }
}
Copy after login

Related recommendations: golang tutorial

The above is the detailed content of What is the method to implement timer in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template