Skip to content

Instantly share code, notes, and snippets.

@ajpen
Created April 10, 2018 20:58
Show Gist options
  • Select an option

  • Save ajpen/937fec8baeaa04fff8ddebf51666b332 to your computer and use it in GitHub Desktop.

Select an option

Save ajpen/937fec8baeaa04fff8ddebf51666b332 to your computer and use it in GitHub Desktop.
Interval is a wrapper for the ticker and tick functions in the time library. It wraps everything into a single function call. The function passed is executed in a goroutine and should prepared as such. All intervals started will spawn a goroutine in the background, which will be responsible for tracking the ticks and starting the tasks. This pre…
// Package interval runs functions(tasks) at specific intervals, wrapping the standard library ticker, Tasks should be designed as goroutine compatible
package interval
import (
"time"
"errors"
)
// NewInterval runs the task after the duration, forever.
func NewInterval(duration time.Duration, task func()) error {
if duration <= 0 {
return errors.New("Duration must be greater than 0")
}
ticks := time.Tick(duration)
go func (task func()) {
for _ = range ticks {
go task()
}
}(task)
return nil
}
// NewTicker runs the task after the duration. The underlying ticker is exposed through ticker
func Ticker(duration time.Duration, task func(), ticker **time.Ticker) error {
if duration <= 0 {
return errors.New("Duration must be greater than 0")
}
*ticker = time.NewTicker(duration)
go func (task func()) {
for _ = range (*ticker).C {
go task()
}
}(task)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment