Golang time.NewTicker()函数及示例

Golang time.NewTicker()函数及示例

在Go语言中,time包提供了确定和查看时间的功能。time中的NewTicker()函数用于输出一个新的Ticker,其中包含一个通道以按照持续时间参数所述的周期传输时间。它有助于设置间隔或删除时钟的“tick”以弥补接收者的缓慢。这里,持续时间“d”必须大于零,否则将发生恐慌错误。您可以使用Stop()方法停止Ticker以释放相关资源。此外,该函数是在time包下定义的。在这里,您需要导入“time”包才能使用这些函数。

语法:

func NewTicker(d Duration) *Ticker

这里,“d”是持续时间,“* Ticker”是Ticker的指针。在这里,Ticker用于保存以间隔供应时钟的“tick”的通道。

返回值:它返回一个包含通道的新的Ticker。

例子1:

// Golang program to illustrate the usage of
// time.NewTicker() function

// Including main package
package main

// Importing fmt and time
import "fmt"
import "time"

// Calling main
func main() {

    // Calling NewTicker method
    d := time.NewTicker(2 * time.Second)

    // Creating channel using make
    // keyword
    mychannel := make(chan bool)

    // Calling Sleep() methpod in go
    // function
    go func() {
        time.Sleep(7 * time.Second)

        // Setting the value of channel
        mychannel <- true
    }()

    // Using for loop
    for {

        // Select statement
        select {

        // Case statement
        case <-mychannel:
            fmt.Println("Completed!")
            return

        // Case to print current time
        case tm := <-d.C:
            fmt.Println("The Current time is: ", tm)
        }
    }
} 

输出:

The Current time is: 2020-04-08 14:54:20.143952489 +0000 UTC m=+2.000223531
The Current time is: 2020-04-08 14:54:22.143940032 +0000 UTC m=+4.000211079
The Current time is: 2020-04-08 14:54:24.143938623 +0000 UTC m=+6.000209686
Completed!

在这里,使用for循环打印当前时间,直到循环停止,并且此时间在代码中指定的“tick”之后以固定间隔打印。这里是2秒。因此,在上面每隔2秒钟打印当前时间。在这里,Ticker必须在三次之后停止,因为限制为7秒,第三个“tick”后只剩1秒。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程