How to set timer in 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.
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 }
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 }
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 }
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 // 通过通道阻塞,让任务可以执行完指定的次数。
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
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 通道。")
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 通道。") }
// 阻塞一下,等待主进程结束 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 没干活了...")
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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. �...

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

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

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? When using GoLand for Go language development, many developers will encounter custom structure tags...

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, ...

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...

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...
