Timeouts in Go
Go: Timeouts
Timeouts can be used to limit the amount of time a function or operation is allowed to run.
Timeouts can be useful when you want to ensure that your program doesn't get stuck waiting for something that may never happen.
How to implements Timeout in Go
One way to implement timeouts in Go is to use the time
package. The time
package provides a Timer
type that can be used to schedule a function call to occur after a specified amount of time. If the timer expires before the function is called, the timer's C
channel will be signaled.
Here is an example -
package main
import (
"fmt"
"time"
)
func main() {
timeout := 5 * time.Second
timer := time.NewTimer(timeout)
// simulate a long-running operation
time.Sleep(10 * time.Second)
select {
case <-timer.C:
fmt.Println("Timeout!")
default:
fmt.Println("Operation completed successfully!")
}
}
There are other ways to implement timeouts in Go, depending on the specific use case. For example, you could use a context.Context
object to propagate a cancellation signal throughout your program, or you could use channels to implement your own timeout logic. However, the time
package is a good place to start if you just need a simple way to limit the amount of time a function or operation is allowed to run.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go