ribbit/scheduler.go

52 lines
732 B
Go

package main
import "time"
const (
RESULT_OK = 0
RESULT_ERR = 1
)
type JobScheduler struct {
Jobs []Job
}
func NewJobScheduler() *JobScheduler {
return new(JobScheduler)
}
func (s *JobScheduler) AddJob(j *Job) {
s.Jobs = append(s.Jobs, *j)
}
func (s *JobScheduler) Run() {
for _, j := range s.Jobs {
if j.ShouldRunNow() {
j.Run()
}
}
}
type Job struct {
freq time.Duration
lastRun time.Time
lastResult int
action func() int
}
func NewJob(a func() int, f time.Duration) *Job {
j := new(Job)
j.action = a
j.freq = f
return j
}
func (j *Job) ShouldRunNow() bool {
return time.Now().After(j.lastRun.Add(j.freq))
}
func (j *Job) Run() {
j.lastResult = j.action()
j.lastRun = time.Now()
}