53 lines
1007 B
Go
53 lines
1007 B
Go
package app
|
|
|
|
import (
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/robfig/cron/v3"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type Scheduler struct {
|
|
filePath string
|
|
lastSuccessTime map[string]time.Time
|
|
}
|
|
|
|
func NewScheduler(filePath string) (*Scheduler, error) {
|
|
s := Scheduler{filePath: filePath}
|
|
data, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
err = yaml.Unmarshal(data, &s.lastSuccessTime)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
func (s *Scheduler) Save() error {
|
|
data, err := yaml.Marshal(&s.lastSuccessTime)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(s.filePath, data, 0644)
|
|
}
|
|
|
|
func (s *Scheduler) Good(name string) {
|
|
s.lastSuccessTime[name] = time.Now()
|
|
}
|
|
|
|
func (s *Scheduler) ShouldDownload(name string, scheduleSpec string) (bool, error) {
|
|
lastSuccess, ok := s.lastSuccessTime[name]
|
|
if !ok {
|
|
return true, nil
|
|
}
|
|
cron, err := cron.ParseStandard(scheduleSpec)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n := cron.Next(lastSuccess)
|
|
return n.Before(time.Now()), nil
|
|
}
|