當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang time.NewTimer()用法及代碼示例

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的NewTimer()函數用於創建新的計時器,該計時器將至少在持續時間“d”之後在其通道上傳輸實際時間。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func NewTimer(d Duration) *Timer

這裏,* Timer是指向計時器的指針。

返回值:它返回一個通道,通知計時器必須等待多長時間。

範例1:



// Golang program to illustrate the usage of 
// NewTimer() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Calling NewTimer method 
    newtimer:= time.NewTimer(5 * time.Second) 
  
    // Notifying the channel 
    <-newtimer.C 
  
    // Printed after 5 seconds 
    fmt.Println("Timer is inactivated") 
}

輸出:

Timer is inactivated

在此,在運行代碼5秒鍾後,將打印上述輸出,因為在該指定時間之後,該通道將被通知計時器已被禁用。

範例2:

// Golang program to illustrate the usage of 
// NewTimer() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Calling NewTimer method 
    newtimer:= time.NewTimer(time.Second) 
  
    // Notifying channel under go function 
    go func() { 
        <-newtimer.C 
  
        // Printed when timer is fired 
        fmt.Println("timer inactivated") 
    }() 
  
    // Calling stop method to stop the 
    // timer before inactivation 
    stoptimer:= newtimer.Stop() 
  
    // If the timer is stopped then the 
    // below string is printed 
    if stoptimer { 
        fmt.Println("The timer is stopped!") 
    } 
  
    // Calling sleep method to stop the 
    // execution at last 
    time.Sleep(4 * time.Second) 
}

輸出:

The timer is stopped!

在上述方法中,計時器在停用之前已停止,因為此處調用了stop方法以停止計時器。最後,使用睡眠方法退出程序。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.NewTimer() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。