2019-05-31 02:43:23 +03:00
|
|
|
package sync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"time"
|
|
|
|
|
2020-02-23 16:45:20 +03:00
|
|
|
log "github.com/micro/go-micro/v2/logger"
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/sync/leader/etcd"
|
|
|
|
"github.com/micro/go-micro/v2/sync/task"
|
|
|
|
"github.com/micro/go-micro/v2/sync/task/local"
|
2019-05-31 02:43:23 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type syncCron struct {
|
|
|
|
opts Options
|
|
|
|
}
|
|
|
|
|
|
|
|
func backoff(attempts int) time.Duration {
|
|
|
|
if attempts == 0 {
|
|
|
|
return time.Duration(0)
|
|
|
|
}
|
|
|
|
return time.Duration(math.Pow(10, float64(attempts))) * time.Millisecond
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *syncCron) Schedule(s task.Schedule, t task.Command) error {
|
|
|
|
id := fmt.Sprintf("%s-%s", s.String(), t.String())
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
// run the scheduler
|
|
|
|
tc := s.Run()
|
|
|
|
|
|
|
|
var i int
|
|
|
|
|
|
|
|
for {
|
|
|
|
// leader election
|
|
|
|
e, err := c.opts.Leader.Elect(id)
|
|
|
|
if err != nil {
|
2020-02-23 16:45:20 +03:00
|
|
|
log.Errorf("[cron] leader election error: %v", err)
|
2019-05-31 02:43:23 +03:00
|
|
|
time.Sleep(backoff(i))
|
|
|
|
i++
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
i = 0
|
|
|
|
r := e.Revoked()
|
|
|
|
|
|
|
|
// execute the task
|
|
|
|
Tick:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
// schedule tick
|
|
|
|
case _, ok := <-tc:
|
|
|
|
// ticked once
|
|
|
|
if !ok {
|
|
|
|
break Tick
|
|
|
|
}
|
|
|
|
|
2020-02-23 16:45:20 +03:00
|
|
|
log.Infof("[cron] executing command %s", t.Name)
|
2019-05-31 02:43:23 +03:00
|
|
|
if err := c.opts.Task.Run(t); err != nil {
|
2020-02-23 16:45:20 +03:00
|
|
|
log.Errorf("[cron] error executing command %s: %v", t.Name, err)
|
2019-05-31 02:43:23 +03:00
|
|
|
}
|
|
|
|
// leader revoked
|
|
|
|
case <-r:
|
|
|
|
break Tick
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// resign
|
|
|
|
e.Resign()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCron(opts ...Option) Cron {
|
|
|
|
var options Options
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
|
|
|
if options.Leader == nil {
|
2019-10-03 13:26:24 +03:00
|
|
|
options.Leader = etcd.NewLeader()
|
2019-05-31 02:43:23 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if options.Task == nil {
|
|
|
|
options.Task = local.NewTask()
|
|
|
|
}
|
|
|
|
|
|
|
|
return &syncCron{
|
|
|
|
opts: options,
|
|
|
|
}
|
|
|
|
}
|