func dailyCleanupJob(app core.App) error {
jm := jobs.GetManager()
return jm.RegisterJob("dailyCleanup", "Daily Cleanup Job",
"Automated maintenance job that runs daily at 2 AM to clean up completed todos older than 30 days",
"0 2 * * *", func(el *jobs.ExecutionLogger) {
el.Start("Daily Cleanup Job")
el.Info("Cleanup job started at: %s", time.Now().Format("2006-01-02 15:04:05"))
collection, err := app.FindCollectionByNameOrId("todos")
if err != nil {
el.Error("Failed to find todos collection: %v", err)
el.Fail(err)
return
}
el.Success("Found todos collection, proceeding with cleanup...")
cutoffDate := time.Now().AddDate(0, 0, -30)
el.Info("Cleaning up todos older than: %s", cutoffDate.Format("2006-01-02"))
filter := "completed = true && created < {:cutoff}"
records, err := app.FindRecordsByFilter(collection, filter, "", 100, 0, map[string]any{
"cutoff": cutoffDate.Format("2006-01-02 15:04:05.000Z"),
})
if err != nil {
el.Error("Failed to find old todos: %v", err)
el.Fail(err)
return
}
el.Info("Found %d old completed todos to clean up", len(records))
deletedCount := 0
for _, record := range records {
if err := app.Delete(record); err != nil {
el.Error("Failed to delete todo %s: %v", record.Id, err)
} else {
deletedCount++
}
}
el.Statistics(map[string]interface{}{
"total_found": len(records),
"deleted": deletedCount,
"failed": len(records) - deletedCount,
})
el.Complete(fmt.Sprintf("Deleted %d/%d records", deletedCount, len(records)))
})
}