在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的Tick()函數是NewTicker函數的實用程序包裝。它僅允許訪問滴答通道。此外,對於不需要關閉股票行情收錄器的客戶來說,股票行情是有益的。如果指定的持續時間小於或等於0,則Tick方法返回nil。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。
用法:
func Tick(d Duration) <-chan Time
在這裏,d是股票行情交易的持續時間,而chan是股票行情的交易通道。
注意:股票行情用於在規定的時間定期執行某些操作。
返回值:定期間隔後返回當前日期和實際時間。如果d <= 0,則返回nil。
範例1:
// Golang program to illustrate the usage of
// Tick() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Defining UTCtime
func UTCtime() string {
return ""
}
// Main function
func main() {
// Calling Tick method
// using range keyword
for tick:= range time.Tick(3 * time.Second) {
// Prints UTC time and date
fmt.Println(tick, UTCtime())
}
}
輸出:
2020-04-02 03:16:22.27131713 +0000 UTC m=+3.000249815 2020-04-02 03:16:25.271334601 +0000 UTC m=+6.000267330 2020-04-02 03:16:28.271312516 +0000 UTC m=+9.000245191 2020-04-02 03:16:31.271369788 +0000 UTC m=+12.000302595 2020-04-02 03:16:34.271309254 +0000 UTC m=+15.000241952 2020-04-02 03:16:37.271324182 +0000 UTC m=+18.000256858 2020-04-02 03:16:40.271322789 +0000 UTC m=+21.000255504 2020-04-02 03:16:43.271295568 +0000 UTC m=+24.000228305......so on
在這裏,我們使用range關鍵字來迭代通道。在此,在固定的時間間隔後返回當前日期和時間。因此,在不同的運行時輸出是不同的。直到您終止循環,循環才會停止。
範例2:
// Golang program to illustrate the usage of
// Tick() function
// Including main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Defining UTCtime
func UTCtime() string {
return ""
}
// Main function
func main() {
// Calling Tick method using range
// keyword
for tick:= range time.Tick(-1 * time.Second) {
// Prints UTC time and date
fmt.Println(tick, UTCtime())
}
}
輸出:
fatal error:all goroutines are asleep - deadlock! goroutine 1 [chan receive (nil chan)]: main.main() /home/runner/SociableInsubstantialCommunication/main.go:23 +0x149
這裏,在上麵的代碼中,指定的持續時間為負數,因此返回nil並發生錯誤。
相關用法
- 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.Tick() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。