Home Backend Development Golang How to set timer in go language

How to set timer in go language

Dec 16, 2020 am 10:59 AM
go language

How to set a timer in go language: 1. Create it through the "time.NewTicker()" method, where the ticker will be triggered according to the set interval; 2. Create it through the "time.NewTimer()" method , where timer will only execute one word; 3. Use "After()" to create.

How to set timer in go language

Environment of this article: Windows 7 system, Go1.11.2 version, this article is applicable to all brands of computers.

Recommended: "golang tutorial"

Using timers in Go language

GO language provides three ways to use timers in the time package:

1. The first one: ticker

// 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
}
Copy after login

Created through time.NewTicker(). In this type, the ticker will be triggered continuously according to the set interval. , unless the operation is actively terminated.

2. The second type: timer##

// 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
}
Copy after login

pass time.NewTimer() Create, of this type, the timer will only be executed once. Of course, you can call timer.Reset() after execution. Make the timer work again, with the possibility to change the interval.

3. The third type: After()

// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
	return NewTimer(d).C
}
Copy after login

As you can see from the code, After() actually It is a syntactic sugar for Timer.



The following demonstrates the use of the three methods through code:

1.Ticker

ticker := time.NewTicker(time.Second * 1) // 运行时长
    ch := make(chan int)
    go func() {
        var x int
        for x < 10 {
            select {
            case <-ticker.C:
                x++
                fmt.Printf("%d\n", x)
            }
        }
        ticker.Stop()
        ch <- 0
    }()
    <-ch                                    // 通过通道阻塞,让任务可以执行完指定的次数。
Copy after login

The ticker is every 1 second Triggered once, that is, one content will be added to ticker.C every second. Finally, by writing a number to ch, the program will be unblocked and continue execution.

2.Timer

timer := time.NewTimer(time.Second * 1) // timer 只能按时触发一次,可通过Reset()重置后继续触发。
    go func() {
        var x int
        for {
            select {
            case <-timer.C:
                x++
                fmt.Printf("%d,%s\n", x, time.Now().Format("2006-01-02 15:04:05"))
                if x < 10 {
                    timer.Reset(time.Second * 2)
                } else {
                    ch <- x
                }
            }
        }
    }()
    <-ch
Copy after login

3.After()

// 阻塞一下,等待主进程结束
    tt := time.NewTimer(time.Second * 10)
    <-tt.C
    fmt.Println("over.")

    <-time.After(time.Second * 4)
    fmt.Println("再等待4秒退出。tt 没有终止,打印出 over 后会看见在继续执行...")
    tt.Stop()
    <-time.After(time.Second * 2)
    fmt.Println("tt.Stop()后, tt 仍继续执行,只是关闭了 tt.C 通道。")
Copy after login

4. We can use these basic method to design your own scheduled task management.

type jobFunc2 func(j *job)

type job struct {
    jf     jobFunc2
    params map[string]interface{}
    ch     chan int
}

func NewJob() *job {
    return &job{
        params: make(map[string]interface{}),
        ch:     make(chan int),
    }
}

func (j *job) Run(t time.Duration) {
    ticker := time.NewTicker(time.Second * t)
    go func() {
        for {
            select {
            case <-ticker.C:
                j.jf(j)
            case <-j.ch:
                fmt.Println("收到结束指令")
                ticker.Stop()
                break
            }
        }
    }()

}

func main() {
    j := NewJob()
    j.jf = func(jj *job) {
        fmt.Println("定时任务执行...", time.Now().Format("15:04:05 2006-02-01"), jj.params)
    }
    j.params["p1"] = "第一个参数"
    j.params["p2"] = 100
    j.Run(1)

    // 阻塞一下,等待主进程结束
    tt := time.NewTimer(time.Second * 10)
    <-tt.C
    fmt.Println("over.")

    <-time.After(time.Second * 4)
    fmt.Println("再等待4秒退出。tt 没有终止,打印出 over 后会看见在继续执行...")
    tt.Stop()
    <-time.After(time.Second * 2)
    fmt.Println("tt.Stop()后, tt 仍继续执行,只是关闭了 tt.C 通道。")
}
Copy after login

Screenshot of some execution results:

Finally, I would like to add that the execution of the task is terminated through the channel.

// 阻塞一下,等待主进程结束
    tt := time.NewTimer(time.Second * 10)
    <-tt.C
    fmt.Println("over.")

    <-time.After(time.Second * 4)
    fmt.Println("再等待4秒退出。tt 没有终止,打印出 over 后会看见在继续执行...")
    tt.Stop()
    <-time.After(time.Second * 2)
    fmt.Println("tt.Stop()后, tt 仍继续执行,只是关闭了 tt.C 通道。")
    j.ch <- 0
    <-time.After(time.Second * 2)
    fmt.Println("又等了2秒钟...这两秒钟可以看到 tt 没干活了...")
Copy after login


When writing in GO language, you must be proficient in using

channel.

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles