跳转到主要内容

在本教程中,我们将研究 Go 中的代码以及如何在自己的 Go 应用程序中有效地使用代码。

当您需要在给定的时间间隔内重复执行某项操作时,Tickers 非常有用,我们可以将 Tickers 与 goroutines 结合使用,以便在我们的应用程序后台运行这些任务。

行情(Tickers )与计时器


在我们深入研究之前,了解代码和计时器之间的区别很有用。

  • Tickers - 这些非常适合重复任务
  • 计时器(Timers ) - 这些用于一次性任务

一个简单的例子


让我们从一个非常简单的开始,我们每隔 5 秒重复运行一个简单的 fmt.Println 语句。

main.go

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println("Go Tickers Tutorial")
	// this creates a new ticker which will
    // `tick` every 1 second.
    ticker := time.NewTicker(1 * time.Second)
	
    // for every `tick` that our `ticker`
    // emits, we print `tock`
	for _ = range ticker.C {
		fmt.Println("tock")
	}
}

现在,当我们运行它时,我们的 Go 应用程序将无限期地运行,直到我们 ctrl-c 退出程序并且每 1 秒它会打印出 tock 到终端。

$ go run main.go

Go Tickers Tutorial
Tock
Tock
^Csignal: interrupt


在后台运行


所以我们已经能够实现一个非常简单的 Go 应用程序,它使用一个ticker 来重复执行一个动作。但是,如果我们希望在 Go 应用程序的后台执行此操作会发生什么?

好吧,如果我们有一个想要在后台运行的任务,我们可以将遍历 ticker.C 的 for 循环移动到一个 goroutine 中,这将允许我们的应用程序执行其他任务。

让我们移动用于创建代码的代码并循环到一个名为 backgroundTask() 的新函数中,然后在我们的 main() 函数中,我们将使用 go 关键字将其称为 goroutine,如下所示:

main.go

package main

import (
	"fmt"
	"time"
)

func backgroundTask() {
	ticker := time.NewTicker(1 * time.Second)
	for _ = range ticker.C {
		fmt.Println("Tock")
	}
}

func main() {
	fmt.Println("Go Tickers Tutorial")

	go backgroundTask()
	
    // This print statement will be executed before
    // the first `tock` prints in the console
	fmt.Println("The rest of my application can continue")
	// here we use an empty select{} in order to keep
    // our main function alive indefinitely as it would
    // complete before our backgroundTask has a chance
    // to execute if we didn't.
	select{}

}

很酷,所以如果我们继续运行它,我们应该看到我们的 main() 函数在我们的后台任务 goroutine 启动后继续执行。

$ go run main.go

Go Tickers Tutorial
The rest of my application can continue
Tock
Tock
Tock
^Csignal: interrupt


结论


因此,在本教程中,我们研究了如何在自己的 Go 应用程序中使用代码来执行可重复任务之前,无论是在主线程上还是作为后台任务。

文章链接