runner

package module
v0.0.0-...-9f99df8 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2021 License: MIT Imports: 1 Imported by: 10

README

runner

Interruptable goroutines.

Usage

task := runner.Go(func(shouldStop runner.S) error {
  // do setup work
  defer func(){
    // do tear-down work
  }()
  for {

  	// do stuff

  	// periodically check to see if we should
  	// stop or not.
  	if shouldStop() {
  		break
  	}
  }
  return nil // no errors
})

At any time, from any place, you can stop the code from executing:

task.Stop()
select {
	case <-task.StopChan():
		// task successfully stopped
	case <-time.After(1 * time.Second):
		// task didn't stop in time
}

// execution continues once the code has stopped or has
// timed out.

if task.Err() != nil {
	log.Fatalln("task failed:", task.Err())
}
  • To see if the task is running, you can call task.Running()
  • To see if the task has errored, you can check task.Err()

Documentation

Overview

Package runner provides interruptable goroutines.

task := runner.Go(func(shouldStop runner.S) error {
  // do setup
  // defer func(){
  //   // do teardown
  // }
  for {
    // do some work
    if shouldStop() {
      break
    }
  }
  return nil // any errors?
})

// meanwhile...
// stop the task
task.Stop()

// wait for it to stop (or time out)
select {
  case <-task.StopChan():
    // stopped
  case <-time.After(1 * time.Second):
    log.Fatalln("task didn't stop quickly enough")
}

// check errors
if task.Err() != nil {
  log.Fatalln("task failed:", task.Err())
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type S

type S func() bool

S is a function that will return true if the goroutine should stop executing.

type Task

type Task struct {
	ID string
	// contains filtered or unexported fields
}

Task represents an interruptable goroutine.

func Go

func Go(fn func(S) error) *Task

Go executes the function in a goroutine and returns a Task capable of stopping the execution.

func (*Task) Err

func (t *Task) Err() error

Err gets the error returned by the goroutine.

func (*Task) Running

func (t *Task) Running() bool

Running gets whether the goroutine is running or not.

func (*Task) Stop

func (t *Task) Stop()

Stop tells the goroutine to stop.

func (*Task) StopChan

func (t *Task) StopChan() <-chan struct{}

StopChan gets the stop channel for this task. Reading from this channel will block while the task is running, and will unblock once the task has stopped (because the channel gets closed).

Jump to

Keyboard shortcuts

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