asynctask

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2020 License: MIT Imports: 6 Imported by: 0

README

asynctask

Go Report Card Build Status codecov GoDoc Release

Golang handy goroutine runner.

This package aim to simplify goroutine management.

You can run goroutine and get result from it without make channel or use waitgroup. Just define the function and let this package handle the rest for you.

Installation

Use go get

go get github.com/ramabmtr/asynctask

Then import it in your code

import "github.com/ramabmtr/asynctask"

Usage

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ramabmtr/asynctask"
)

func main() {
	asyncTask := asynctask.NewAsyncTask(context.Background())

	// Run first task
	asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
		time.Sleep(3 * time.Second)
		return "test1", nil
	}).Register("taskID1")

	// Run second task
	asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
		time.Sleep(5 * time.Second)
		return true, nil
	}).Register("taskID2")

	// Wait all task to complete
	// if one of runner return error, asynctask will raise that error immediately
	err := asyncTask.StartAndWait()
	if err != nil {
		fmt.Println(err)
		return
	}

	result1, err := asynctask.ResultString(asyncTask.GetResult("taskID1"))
	if err != nil {
		fmt.Println(err)
		return
	}

	result2, err := asynctask.ResultBool(asyncTask.GetResult("taskID2"))
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(result1) // test
	fmt.Println(result2) // true
}

asynctask will raise error immediately if one of runner return error.

you can override it with asyncTask.CancelOnError(false).

asyncTask := asynctask.NewAsyncTask(context.Background())

// Run first task
asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
	return nil, fmt.Errorf("test error")
}).Register("taskID1")

// Run second task
asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
	time.Sleep(time.Second)
	return true, nil
}).Register("taskID2")

// this code will return error as soon as the first task return an error
// it wont wait for second task to complete by default
// uncomment code below to override this behaviour
// asyncTask.CancelOnError(false)
err := asyncTask.Wait() // err == test error

If you want to run multiple runner with same ID, you can set with SetMultiple().

This suit for creating runner inside the loop. The result will be slice of interface.

asyncTask := asynctask.NewAsyncTaskRunner(context.Background())
for i := 0; i < 10; i++ {
	asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
		return "test", nil
	}).SetMultiple().Register("taskID")
}

// Wait all task to complete
err := asyncTask.Wait()
if err != nil {
    fmt.Println(err)
    return
}

result := asyncTask.GetResult("taskID")
fmt.Println(result) // [test test ... test]

You can also pass param to runner with SetParam(param interface{})

asyncTask.NewRunner().SetFunc(func(p interface{}) (interface{}, error) {
    param, ok := p.(string)
    if !ok {
        return nil, fmt.Errorf("param is not string")
    }
    return param, nil
}).SetParam("param").Register("taskID")

Documentation

Overview

This package aim to simplify goroutine management you can run goroutine and get result from it without make [channel](https://golang.org/doc/effective_go.html#channels) or use [waitgroup](https://golang.org/pkg/sync/#WaitGroup). Just define the function and let this package handle the rest for you

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ResultBool

func ResultBool(i interface{}) (bool, error)

ResultBool parse asynctask runner result to bool return error if actual result is not bool

func ResultInt

func ResultInt(i interface{}) (int, error)

ResultInt parse asynctask runner result to int return error if actual result is not int

func ResultObj

func ResultObj(i interface{}, o interface{}) error

ResultObj parse asynctask runner result to destination interface return error if actual result schema and destination schema is not match

func ResultString

func ResultString(i interface{}) (string, error)

ResultString parse asynctask runner result to string return error if actual result is not string

Types

type BaseAsyncTask added in v1.1.0

type BaseAsyncTask struct {
	// contains filtered or unexported fields
}

BaseAsyncTask hold the base context for asynctask

func NewAsyncTask added in v1.1.0

func NewAsyncTask(ctx context.Context) *BaseAsyncTask

NewAsyncTask create new asynctask runner instance

func (*BaseAsyncTask) CancelOnError added in v1.1.0

func (b *BaseAsyncTask) CancelOnError(flag bool) *BaseAsyncTask

CancelOnError is to flag if an error happen, immediately return or not

func (*BaseAsyncTask) GetResult added in v1.1.0

func (b *BaseAsyncTask) GetResult(id string) interface{}

GetResult is to get result from asynctask by ID

func (*BaseAsyncTask) NewRunner added in v1.1.0

func (b *BaseAsyncTask) NewRunner() *Runner

NewRunner create new asynctask runner

func (*BaseAsyncTask) SetRunnerPoolSize added in v1.1.0

func (b *BaseAsyncTask) SetRunnerPoolSize(size int) *BaseAsyncTask

SetRunnerPoolSize to set max goroutine can run at the same time goroutine will run as soon as the pool worker ready

func (*BaseAsyncTask) StartAndWait added in v1.1.0

func (b *BaseAsyncTask) StartAndWait() error

StartAndWait start the asynctask and wait for all task finish

type Runner added in v1.1.0

type Runner struct {
	// contains filtered or unexported fields
}

Runner hold the base context for asynctask runner

func (*Runner) Register added in v1.1.0

func (r *Runner) Register(id string)

Register is to register runner to asynctask

func (*Runner) SetFunc added in v1.1.0

func (r *Runner) SetFunc(f func(param interface{}) (interface{}, error)) *Runner

SetFunc is to set the function that will be executed

func (*Runner) SetMultiple added in v1.1.0

func (r *Runner) SetMultiple() *Runner

SetMultiple is to set asynctask runner can run multiple times on same ID if runner is set to multiple, the result will become slice of interface

func (*Runner) SetParam added in v1.1.0

func (r *Runner) SetParam(param interface{}) *Runner

SetParam is to set param that will be thrown to executed function

Jump to

Keyboard shortcuts

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