Home >Backend Development >Golang >How to set timer in go language

How to set timer in go language

藏色散人
藏色散人Original
2020-12-16 10:59:084896browse

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
}

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
}

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                                    // 通过通道阻塞,让任务可以执行完指定的次数。

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

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 通道。")
}

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 没干活了...")


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