refactor(cron): migrate cron jobs to foundation scheduler

Replace custom goroutine-based scheduling in cron jobs with centralized
foundation scheduler. Each cron job now exposes a RunOnce method called
by the scheduler instead of managing its own ticker loop.

Changes:
- Remove interval/enabled config from cron job structs
- Convert Start() methods to RunOnce() for all cron jobs
- Add scheduler setup in main.go with configurable intervals
- Update foundation dependency to v0.6.0 for scheduler support
- Update tests to validate RunOnce nil-safety
This commit is contained in:
zenfun
2025-12-31 20:42:25 +08:00
parent 4bcd2b4167
commit 05caed37c2
9 changed files with 62 additions and 139 deletions

View File

@@ -15,8 +15,6 @@ import (
// AlertDetectorConfig holds configuration for alert detection
type AlertDetectorConfig struct {
Enabled bool
Interval time.Duration
ErrorSpikeThreshold float64 // Error rate threshold (0.1 = 10%)
ErrorSpikeWindow time.Duration
QuotaWarningThreshold float64 // Quota usage threshold (0.9 = 90%)
@@ -27,8 +25,6 @@ type AlertDetectorConfig struct {
// DefaultAlertDetectorConfig returns default configuration
func DefaultAlertDetectorConfig() AlertDetectorConfig {
return AlertDetectorConfig{
Enabled: true,
Interval: 1 * time.Minute,
ErrorSpikeThreshold: 0.1, // 10% error rate
ErrorSpikeWindow: 5 * time.Minute,
QuotaWarningThreshold: 0.9, // 90% quota used
@@ -65,29 +61,12 @@ func NewAlertDetector(db, logDB *gorm.DB, rdb *redis.Client, statsService *servi
}
}
// Start begins the alert detection loop
func (d *AlertDetector) Start(ctx context.Context) {
if d == nil || !d.config.Enabled {
// RunOnce executes a single detection cycle. Called by scheduler.
func (d *AlertDetector) RunOnce(ctx context.Context) {
if d == nil || d.db == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
ticker := time.NewTicker(d.config.Interval)
defer ticker.Stop()
d.logger.Info("alert detector started", "interval", d.config.Interval)
for {
select {
case <-ctx.Done():
d.logger.Info("alert detector stopped")
return
case <-ticker.C:
d.detectOnce(ctx)
}
}
d.detectOnce(ctx)
}
// detectOnce runs all detection rules once