planner/sync/service/recur.go

66 lines
1.2 KiB
Go
Raw Normal View History

package service
2024-12-08 11:22:33 +01:00
import (
"log/slog"
"time"
"go-mod.ewintr.nl/planner/item"
)
type Recur struct {
2024-12-09 08:44:19 +01:00
repoSync Syncer
repoRecur Recurrer
logger *slog.Logger
2024-12-08 11:22:33 +01:00
}
2024-12-09 08:44:19 +01:00
func NewRecur(repoRecur Recurrer, repoSync Syncer, interval time.Duration, logger *slog.Logger) *Recur {
2024-12-08 11:22:33 +01:00
r := &Recur{
2024-12-09 08:44:19 +01:00
repoRecur: repoRecur,
repoSync: repoSync,
logger: logger,
2024-12-08 11:22:33 +01:00
}
2024-12-10 07:50:30 +01:00
// go r.Run(interval)
2024-12-08 11:22:33 +01:00
return r
}
2024-12-10 07:50:11 +01:00
func (r *Recur) Run(interval time.Duration) {
2024-12-08 11:22:33 +01:00
ticker := time.NewTicker(interval)
for range ticker.C {
2024-12-10 07:50:11 +01:00
if err := r.Recur(); err != nil {
2024-12-08 11:22:33 +01:00
r.logger.Error("could not recur", "error", err)
}
}
}
2024-12-10 07:50:11 +01:00
func (r *Recur) Recur() error {
2024-12-09 08:44:19 +01:00
items, err := r.repoRecur.RecursBefore(time.Now())
2024-12-08 11:22:33 +01:00
if err != nil {
return err
}
for _, i := range items {
2024-12-09 08:44:19 +01:00
// spawn instance
ne, err := item.NewEvent(i)
if err != nil {
return err
}
2024-12-10 07:50:11 +01:00
y, m, d := i.RecurNext.Date()
ne.Start = time.Date(y, m, d, ne.Start.Hour(), ne.Start.Minute(), 0, 0, time.UTC)
2024-12-09 08:44:19 +01:00
ni, err := ne.Item()
if err != nil {
return err
}
if err := r.repoSync.Update(ni); err != nil {
2024-12-08 11:22:33 +01:00
return err
}
2024-12-09 08:44:19 +01:00
// set next
if err := r.repoRecur.RecursNext(i.ID, i.Recurrer.NextAfter(i.RecurNext)); err != nil {
return err
2024-12-08 11:22:33 +01:00
}
}
2024-12-09 08:44:19 +01:00
return nil
2024-12-08 11:22:33 +01:00
}