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


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

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的After()函數用於等待經過的時間,然後在返回的通道上傳遞實際時間。此外,此函數在時間包下定義。在這裏,您需要導入“time”軟件包才能使用這些函數。

用法:

func After(d Duration) <-chan Time

此處,d是超時之前的持續時間,而chan是發送當前時間的通道。

返回值:它首先等待指定的時間,然後顯示超時。

範例1:



// Golang program to illustrate the usage of 
// After() function in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Creating a channel 
// Using var keyword 
var ch chan int
  
// Main function 
func main() { 
  
    // For loop 
    for i:= 1; i < 6; i++ { 
  
        // Prints these util loop stops 
        fmt.Println("****Welcome to GeeksforGeeks***") 
        fmt.Println("A CS-Portal!") 
    } 
  
    // Select statement 
    select { 
  
    // Using case statement to receive 
    // or send operation on channel and 
    // calling After() method with its 
    // parameter 
    case <-time.After(3 * time.Second):
  
        // Printed when timed out 
        fmt.Println("Time Out!") 
    } 
}

輸出:

****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
****Welcome to GeeksforGeeks***
A CS-Portal!
Time Out!    // Displayed after 3 seconds as mentioned in the above code

在上麵的示例中,我們在select語句下使用了“case”語句,以便在通道上發送操作。此外,在for循環執行3秒後,此處將顯示超時。

範例2:

// Golang program to illustrate the usage of 
// After() function in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Creating a channel 
    // Using make keyword 
    channel:= make(chan string, 2) 
  
    // Select statement 
    select { 
  
    // Using case statement to receive 
    // or send operation on channel 
    case output:= <-channel:
        fmt.Println(output) 
  
    // Calling After() method with its 
    // parameter 
    case <-time.After(5 * time.Second):
  
        // Printed after 5 seconds 
        fmt.Println("Its timeout..") 
    } 
}

輸出:

Its timeout..

在這裏,我們使用了“make”關鍵字來創建頻道,然後像上麵的示例一樣,在select語句下也使用case語句,但是在這裏使用了兩次。第一個用於返回輸出,第二個用於調用通道上的After()方法。此後,將在指定的時間顯示超時。




相關用法


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