Timeout
⏱️ Timeout helpers for Go - limit functions to a maximum execution time
Install / Use
/learn @atomicgo/TimeoutREADME
<p align="center"> <strong><a href="https://pkg.go.dev/atomicgo.dev/timeout#section-documentation" target="_blank">Documentation</a></strong> | <strong><a href="https://github.com/atomicgo/atomicgo/blob/main/CONTRIBUTING.md" target="_blank">Contributing</a></strong> | <strong><a href="https://github.com/atomicgo/atomicgo/blob/main/CODE_OF_CONDUCT.md" target="_blank">Code of Conduct</a></strong> </p>
<p align="center"> <img src="https://raw.githubusercontent.com/atomicgo/atomicgo/main/assets/header.png" alt="AtomicGo"> </p> <p align="center"> <table> <tbody> </tbody> </table> </p> <h3 align="center"><pre>go get atomicgo.dev/timeout</pre></h3> <p align="center"> <table> <tbody> </tbody> </table> </p> <!-- gomarkdoc:embed:start --> <!-- Code generated by gomarkdoc. DO NOT EDIT -->
timeout
import "atomicgo.dev/timeout"
Package timeout provides a simple way to add timeouts to your Go code. The Execute function is blocking, so you can use it as a drop-in replacement for your function calls. Timeouts are often useful in scripts, where you want to limit the execution time of a function.
package main
import (
"atomicgo.dev/timeout"
"fmt"
"time"
)
func main() {
res, err := timeout.Execute(time.Second*2, func() (string, error) {
time.Sleep(time.Second * 1)
return "Hello, World!", nil
})
fmt.Println(res, err)
}
Output
Hello, World! <nil>
package main
import (
"atomicgo.dev/timeout"
"fmt"
"time"
)
func main() {
res, err := timeout.Execute(time.Second*1, func() (string, error) {
time.Sleep(time.Second * 2)
return "Hello, World!", nil
})
fmt.Println(res, err)
}
Output
timeout reached
package main
import (
"atomicgo.dev/timeout"
"errors"
"fmt"
"time"
)
func main() {
res, err := timeout.Execute(time.Second*2, func() (string, error) {
time.Sleep(time.Second * 1)
return "", errors.New("some error") // nolint: goerr113
})
fmt.Println(res, err)
}
Output
some error
Index
Variables
<a name="ErrTimeoutReached"></a>ErrTimeoutReached is returned when the timeout is reached.
var ErrTimeoutReached = errors.New("timeout reached")
<a name="Execute"></a>
func Execute
func Execute[T any](duration time.Duration, fn Function[T]) (T, error)
Execute executes a function and returns the result or an error if the timeout is reached. If the timeout is reached, the Function will be interrupted. If the Function returns an error, the error will be returned.
<a name="Function"></a>
type Function
Function is a function that returns a generic value and an error.
type Function[T any] func() (T, error)
Generated by gomarkdoc
<!-- gomarkdoc:embed:end -->AtomicGo.dev · with ❤️ by @MarvinJWendt | MarvinJWendt.com
