planner/sync/service/recur.go

65 lines
1.1 KiB
Go
Raw Normal View History

2024-12-08 11:22:33 +01:00
package main
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
}
go r.run(interval)
return r
}
func (r *Recur) run(interval time.Duration) {
ticker := time.NewTicker(interval)
for range ticker.C {
if err := r.recur(); err != nil {
r.logger.Error("could not recur", "error", err)
}
}
}
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
}
ne.Start = i.RecurNext // TODO something with time
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
}