asyncwork

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2019 License: MIT Imports: 6 Imported by: 0

README

AsyncWork

GoDoc

AsyncWork schedules and throttles function execution in golang

Examples

Scheduling
var wg sync.WaitGroup
wg.Add(2)

worker, err := asyncwork.New()
if err != nil {
	panic(err)
}
worker.Start()
defer worker.Stop()

worker.PostJob(func(ctx context.Context) error {
	// Long operation 1
	log.Printf("Operation1")
	wg.Done()
	return nil
})

worker.PostJob(func(ctx context.Context) error {
	// Long operation 2
	log.Printf("Operation2")
	wg.Done()
	return nil
})

log.Printf("Pending: %v", worker.Len())
wg.Wait()
log.Printf("Pending: %v", worker.Len())
Output
Pending: 2
Operation1
Operation2
Pending: 0
Throttle

When throttling, only the last call is executed within a timespan

var wg sync.WaitGroup
wg.Add(2)

worker, err := asyncwork.New()
if err != nil {
	panic(err)
}
worker.Start()
defer worker.Stop()

worker.PostJob(func(ctx context.Context) error {
	// Long operation 1
	log.Printf("Operation1")
	wg.Done()
	return nil
})

worker.PostThrottledJob(func(ctx context.Context) error {
	// Long operation 2 is not executed due to throttle
	log.Printf("Operation2")
	return nil
}, 500*time.Millisecond)

worker.PostThrottledJob(func(ctx context.Context) error {
	// Long operation 3
	log.Printf("Operation3")
	return nil
}, 500*time.Millisecond)

<-time.After(600 * time.Millisecond)

worker.PostThrottledJob(func(ctx context.Context) error {
	// Long operation 4
	log.Printf("Operation4")
	wg.Done()
	return nil
}, 500*time.Millisecond)

wg.Wait()
log.Printf("Pending: %v", worker.Len())
Output
Operation1
Operation3
Operation4
Pending: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New() (interfaces.AsyncWork, error)

New creates a new working channel

func NewWithContext

func NewWithContext(ctx context.Context) (interfaces.AsyncWork, error)

NewWithContext creates a new working channel

Types

This section is empty.

Directories

Path Synopsis
examples
schedule command
throttle command

Jump to

Keyboard shortcuts

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