|
4 | 4 | "time" |
5 | 5 |
|
6 | 6 | "github.com/hibiken/asynq" |
| 7 | + "github.com/robfig/cron/v3" |
7 | 8 | "github.com/rs/zerolog" |
8 | 9 | "gorm.io/gorm" |
9 | 10 |
|
@@ -110,9 +111,44 @@ func checkAndEnqueueRefreshTasks(client *asynq.Client, db *gorm.DB, logger zerol |
110 | 111 | return |
111 | 112 | } |
112 | 113 |
|
| 114 | + // Calculate and update NextRefreshAt immediately after scheduling |
| 115 | + // This prevents the scheduler from creating new restores every minute |
| 116 | + now := time.Now() |
| 117 | + nextRefresh := calculateNextRefreshTime(config.RefreshSchedule, now) |
| 118 | + if nextRefresh != nil { |
| 119 | + if err := db.Model(&config).Update("next_refresh_at", nextRefresh).Error; err != nil { |
| 120 | + logger.Error(). |
| 121 | + Err(err). |
| 122 | + Str("config_id", config.ID). |
| 123 | + Msg("Failed to update next_refresh_at") |
| 124 | + } else { |
| 125 | + logger.Info(). |
| 126 | + Str("config_id", config.ID). |
| 127 | + Time("next_refresh_at", *nextRefresh). |
| 128 | + Msg("Updated next_refresh_at") |
| 129 | + } |
| 130 | + } |
| 131 | + |
113 | 132 | logger.Info(). |
114 | 133 | Str("config_id", config.ID). |
115 | 134 | Str("database_id", database.ID). |
116 | 135 | Bool("schema_only", config.SchemaOnly). |
117 | 136 | Msg("Refresh restore task enqueued successfully") |
118 | 137 | } |
| 138 | + |
| 139 | +// calculateNextRefreshTime calculates next refresh time from cron schedule |
| 140 | +func calculateNextRefreshTime(cronExpr string, from time.Time) *time.Time { |
| 141 | + if cronExpr == "" { |
| 142 | + return nil |
| 143 | + } |
| 144 | + |
| 145 | + // Parse cron expression (standard 5-field format: minute hour day-of-month month day-of-week) |
| 146 | + parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow) |
| 147 | + schedule, err := parser.Parse(cronExpr) |
| 148 | + if err != nil { |
| 149 | + return nil |
| 150 | + } |
| 151 | + |
| 152 | + next := schedule.Next(from) |
| 153 | + return &next |
| 154 | +} |
0 commit comments