2020-07-23 02:37:34 +00:00
|
|
|
package scheduler
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
logging "github.com/ipfs/go-log/v2"
|
2020-07-24 20:11:16 +00:00
|
|
|
|
|
|
|
"golang.org/x/xerrors"
|
2020-07-23 02:37:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var log = logging.Logger("scheduler")
|
|
|
|
|
|
|
|
// Scheduler manages the execution of jobs triggered
|
2020-07-29 23:34:34 +00:00
|
|
|
// by tickers. Not externally configurable at runtime.
|
2020-07-23 02:37:34 +00:00
|
|
|
type Scheduler struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrepareScheduler returns a ready-to-run Scheduler
|
|
|
|
func PrepareScheduler(db *sql.DB) *Scheduler {
|
|
|
|
return &Scheduler{db}
|
|
|
|
}
|
|
|
|
|
2020-07-24 20:11:16 +00:00
|
|
|
func (s *Scheduler) setupSchema(ctx context.Context) error {
|
|
|
|
if err := setupTopMinerByBaseRewardSchema(ctx, s.db); err != nil {
|
|
|
|
return xerrors.Errorf("setup top miners by reward schema", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-07-23 02:37:34 +00:00
|
|
|
// Start the scheduler jobs at the defined intervals
|
|
|
|
func (s *Scheduler) Start(ctx context.Context) {
|
|
|
|
log.Debug("Starting Scheduler")
|
|
|
|
|
2020-07-24 20:11:16 +00:00
|
|
|
if err := s.setupSchema(ctx); err != nil {
|
|
|
|
log.Fatalw("applying scheduling schema", err)
|
|
|
|
}
|
|
|
|
|
2020-07-23 02:37:34 +00:00
|
|
|
go func() {
|
|
|
|
// run once on start after schema has initialized
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
if err := refreshTopMinerByBaseReward(ctx, s.db); err != nil {
|
|
|
|
log.Errorf(err.Error())
|
|
|
|
}
|
2020-07-29 23:34:34 +00:00
|
|
|
refreshTopMinerCh := time.NewTicker(30 * time.Second)
|
2020-07-23 02:37:34 +00:00
|
|
|
defer refreshTopMinerCh.Stop()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-refreshTopMinerCh.C:
|
|
|
|
if err := refreshTopMinerByBaseReward(ctx, s.db); err != nil {
|
|
|
|
log.Errorf(err.Error())
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|