65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package app
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"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 {
|
|
if !errors.Is(err, os.ErrNotExist) {
|
|
return nil, err
|
|
}
|
|
f, err := os.Create(filePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("path:%v does not exist and unable to create: err: %w", filePath, err)
|
|
}
|
|
f.Close()
|
|
log.Printf("file: %v does not exist. Will be created\n", filePath)
|
|
} else {
|
|
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
|
|
}
|