timebox

package module
v0.0.0-...-0c355cf Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2018 License: MIT Imports: 3 Imported by: 0

README

go-timebox Travis Codecov GoDoc go-report

timebox a go function

func ExampleDetail() {
	result, err := timebox.Timebox(time.Second, func() (int, error) {
		// Some heavy operation
		return 42, nil
	})
	// check if Timebox() has an error
	if err != nil {
		panic(err)
	}
	// check if the function has an error
	if result[1] != nil {
		panic(result[1])
	}
	fmt.Printf("The answer is %d\n", result[0].(int))
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsNotAFunctionError

func IsNotAFunctionError(err error) bool

IsNotAFunctionError tests if a error is an NotAFunctionError

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError tests if a error is an TimeoutError

func Timebox

func Timebox(timeout time.Duration, fn interface{}, arguments ...interface{}) (returns []interface{}, err error)

Timebox timeboxes a function to a specific timeout, if the timeout exceeds the err will be an instance of TimeoutError Specify 0 as timeout to wait infinitely

Example
package main

import (
	"time"

	timebox "github.com/Eun/go-timebox"
)

func main() {
	// run time.Sleep(time.Minute), if the call takes longer than a second continue with execution
	timebox.Timebox(time.Second, time.Sleep, time.Minute)
}
Example (CheckCancelInsideTheFunction)
package main

import (
	"time"

	timebox "github.com/Eun/go-timebox"
	"github.com/tevino/abool"
)

func main() {
	canceled := abool.New()
	_, err := timebox.Timebox(time.Second, func() (int, error) {
		time.Sleep(time.Second)
		// did we already cancel?
		if canceled.IsSet() {
			return 0, nil
		}
		time.Sleep(time.Second)
		return 42, nil
	})
	if timebox.IsTimeoutError(err) {
		canceled.Set()
	}
}
Example (InlineFunction)
package main

import (
	"fmt"
	"time"

	timebox "github.com/Eun/go-timebox"
)

func main() {
	result, err := timebox.Timebox(time.Second, func() (int, error) {
		// Some heavy operation
		return 42, nil
	})
	// check if Timebox() has an error
	if err != nil {
		panic(err)
	}
	// check if the function has an error
	if result[1] != nil {
		panic(result[1])
	}
	fmt.Printf("The answer is %d\n", result[0].(int))
}

Types

type NotAFunctionError

type NotAFunctionError struct{}

NotAFunctionError will be returned if the passed parameter for Timebox is not a function

func (NotAFunctionError) Error

func (NotAFunctionError) Error() string

type TimeoutError

type TimeoutError struct{}

TimeoutError will be returned if the timeout exceeds

func (TimeoutError) Error

func (TimeoutError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL