package morningalarm import ( "encoding/json" "os" "time" "github.com/robfig/cron/v3" ) func (ma *MorningAlarm) nextAlarm() *time.Time { if len(ma.cr.Entries()) == 0 { return nil } min := ma.cr.Entries()[0].Next for _, entry := range ma.cr.Entries() { if entry.Next.Before(min) { min = entry.Next } } return &min } func (ma *MorningAlarm) addAlarm(spec string, name string) (cron.EntryID, error) { id, err := ma.cr.AddFunc(spec, ma.fireAlarm) if err != nil { return 0, err } ma.alarms = append(ma.alarms, alarm{ id: id, Time: spec, Name: name, }) return id, nil } func (ma *MorningAlarm) saveAlarms() error { content, err := json.Marshal(ma.alarms) if err != nil { return err } err = os.WriteFile("alarms.json", content, 0644) if err != nil { return err } return nil } func (ma *MorningAlarm) loadAlarms() error { if _, err := os.Stat("alarms.json"); os.IsNotExist(err) { ma.alarms = []alarm{} return nil } content, err := os.ReadFile("alarms.json") if err != nil { return err } var ent []alarm err = json.Unmarshal(content, &ent) if err != nil { return err } for _, entry := range ent { _, err := ma.addAlarm(entry.Time, entry.Name) if err != nil { return err } } return nil } func (ma *MorningAlarm) fireAlarm() { ma.playWakeUpMusic() }