async

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2020 License: BSD-3-Clause Imports: 4 Imported by: 0

Documentation

Overview

Package async provides the types, functions, and methods to facilitate the safe running and closing of asynchronous tasks.

To get started, let's take a look at async.Job. As you can see in the example below we are defining an async.Job called myJob, and stubbing out the Run and Close fields. These fields are functions that will control the running and safe closing of your Job.

myJob := async.Job{
	Run: func() {
		// do my thing
	},
	Close: func() {
		// close my thing
	},
}

Running an HTTP server with async.Job might look like the following:

myJob := async.Job{
	Run: func() error {
		return http.ListenAndServe()
	},
	Close: func() error {
		return s.Shutdown(context.Background())
	},
}

myJob.Execute()

By default, the function defined for async.Job.Close will trigger when a syscall.SIGINT or syscall.SIGTERM is received. You can modify these defaults by setting your own on the async.Job.

myJob := async.Job{
	Run: func() error {
		return http.ListenAndServe()
	},
	Close: func() error {
		return s.Shutdown(context.Background())
	},
	Signals: []os.Signal{syscall.SIGHUP},
}

myJob.Execute()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Job

type Job struct {
	// Run And Close functions.
	// Both required iff using Execute() or RunWithClose().
	Run   func() error
	Close func() error

	// Signals is a slice of os.Signal to notify on.
	// This is used by Execute(). Defaults to SIGINT and SIGTERM.
	Signals []os.Signal

	// todo: decide if this is in fact useful
	// Pointer to next Job. Useful for chaining order of operations.
	Next *Job
	// contains filtered or unexported fields
}

func (*Job) Execute

func (j *Job) Execute() error

Execute is a blocking method that calls RunWithClose and sets up a channel to listen for signals defined in Job.Signals. Will return error if RunWithClose results in an error from either Job.Run or Job.Close.

func (*Job) RunWithClose

func (j *Job) RunWithClose() (sig, ack chan int, err chan error)

RunWithClose executes the function defined in Job.Run as a goroutine. It returns three channels to the caller to facilitate communication. Once signaled on the "sig" channel, the function defined in Job.Close will be called. Once Job.Close has finished, the caller is sent a final message on the "ack" channel. All errors are reported through the "err" channel.

func (*Job) SignalToClose

func (j *Job) SignalToClose()

Helper function to signal a job to close.

type SafeCloser

type SafeCloser interface {
	RunWithClose() (sig, ack chan int, err chan error)
}

Jump to

Keyboard shortcuts

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