golang tutorial - Timeout In Golang | Timeout Golang - golang - go programming language - google go - go language - go program - google language



The term timeout or time-out has several meanings, including:

  • A network parameter related to an enforced event designed to occur at the conclusion of a predetermined elapsed time.
  • A specified period of time that will be allowed to elapse in a system before a specified event is to take place, unless another specified event occurs first.
  • A timeout condition can be canceled by the receipt of an appropriate time-out cancellation signal.
  • golang timout
  • An event that occurs at the end of a predetermined period of time that began at the occurrence of another specified event. The timeout can be prevented by an appropriate signal.
  • Timeouts are very important for programs that connect to external resources or that otherwise need to bound execution time.
  • Implementing timeouts in Go is very easy and elegant thanks to channels and select.
package main

	import "time"
import "fmt"

	func main() {
// For our example, suppose we’re executing an external call that returns its result on a channel c1 after 2s.
	    c1 := make(chan string, 1)
    go func() {
        time.Sleep(time.Second * 2)
        c1 <- "result 1"
    }()
/// Here’s the select implementing a timeout. res := <-c1awaits the result and <-Time.After awaits a value to be sent after the timeout of 1s. Since select proceeds with the first receive that’s ready, we’ll take the timeout case if the operation takes more than the allowed 1s.
	    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(time.Second * 1):
        fmt.Println("timeout 1")
    }
// If we allow a longer timeout of 3s, then the receive from c2will succeed and we’ll print the result.
	    c2 := make(chan string, 1)
    go func() {
        time.Sleep(time.Second * 2)
        c2 <- "result 2"
    }()
    select {
    case res := <-c2:
        fmt.Println(res)
    case <-time.After(time.Second * 3):
        fmt.Println("timeout 2")
    }
}
click below button to copy the code. By - golang tutorial - team
 if statement
golang , gopro , google go , golang tutorial , google language , go language , go programming language

Output for the above go program – timeout

 // Running this program shows the first operation timing out and the second succeeding.
	$ go run timeouts.go 
timeout 1
result 2

Related Searches to Timeout In Golang | Timeout Golang