在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的NewTicker()函數用於輸出包含通道的新的股票代碼,以便以duration參數指定的周期發送時間。在設置時間間隔或滴答器的滴答聲方麵很有幫助,以彌補速度較慢的收件人。在此,持續時間‘d’必須大於零,否則會發生緊急錯誤。然後,您可以使用Stop()方法終止股票行情收錄器,以釋放相關資源。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。
用法:
func NewTicker(d Duration) *Ticker
在這裏,“d”是持續時間,* 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秒的常規間隔後,當前時間會顯示在上方。在這裏,股票代碼必須在三次之後停止,因為限製為7秒,並且在第三筆代碼之後僅剩1秒。
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.NewTicker() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。