|
| 1 | +package queue |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/redis/go-redis/v9" |
| 8 | +) |
| 9 | + |
| 10 | +// startScheduler starts the background scheduler loop that checks for scheduled jobs. |
| 11 | +// It polls Redis at the specified interval to find jobs ready to run. |
| 12 | +func (q *Queue) startScheduler(interval time.Duration) { |
| 13 | + if interval == 0 { |
| 14 | + interval = 5 * time.Second // Default polling interval |
| 15 | + } |
| 16 | + |
| 17 | + q.schedulerTicker = time.NewTicker(interval) |
| 18 | + q.schedulerDone = make(chan struct{}) |
| 19 | + |
| 20 | + go func() { |
| 21 | + for { |
| 22 | + select { |
| 23 | + case <-q.schedulerTicker.C: |
| 24 | + q.processScheduledJobs() |
| 25 | + case <-q.schedulerDone: |
| 26 | + return |
| 27 | + } |
| 28 | + } |
| 29 | + }() |
| 30 | + |
| 31 | + q.formatLog(LoggerInfo, "Scheduler started with %v interval", interval) |
| 32 | +} |
| 33 | + |
| 34 | +// stopScheduler stops the scheduler gracefully. |
| 35 | +func (q *Queue) stopScheduler() { |
| 36 | + if q.schedulerTicker != nil { |
| 37 | + q.schedulerTicker.Stop() |
| 38 | + close(q.schedulerDone) |
| 39 | + q.formatLog(LoggerInfo, "Scheduler stopped") |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// ScheduleJob adds a job to the scheduled set with the given run time. |
| 44 | +// The job will be executed when the current time reaches or exceeds runAt. |
| 45 | +func (q *Queue) ScheduleJob(jobId string, runAt time.Time) error { |
| 46 | + score := float64(runAt.Unix()) |
| 47 | + _, err := q.client.ZAdd(q.ctx, q.schedulerKey, redis.Z{ |
| 48 | + Score: score, |
| 49 | + Member: jobId, |
| 50 | + }).Result() |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("failed to schedule job: %w", err) |
| 53 | + } |
| 54 | + q.formatLog(LoggerInfo, "Scheduled job %s to run at %s", jobId, runAt.Format(time.RFC3339)) |
| 55 | + return nil |
| 56 | +} |
| 57 | + |
| 58 | +// GetScheduledJobs retrieves all scheduled jobs with their scheduled times. |
| 59 | +func (q *Queue) GetScheduledJobs() ([]ScheduledJobInfo, error) { |
| 60 | + // Get all jobs with scores |
| 61 | + results, err := q.client.ZRangeWithScores(q.ctx, q.schedulerKey, 0, -1).Result() |
| 62 | + if err != nil { |
| 63 | + return nil, fmt.Errorf("failed to get scheduled jobs: %w", err) |
| 64 | + } |
| 65 | + |
| 66 | + scheduledJobs := make([]ScheduledJobInfo, 0, len(results)) |
| 67 | + for _, z := range results { |
| 68 | + jobId, ok := z.Member.(string) |
| 69 | + if !ok { |
| 70 | + continue |
| 71 | + } |
| 72 | + scheduledJobs = append(scheduledJobs, ScheduledJobInfo{ |
| 73 | + JobId: jobId, |
| 74 | + RunAt: time.Unix(int64(z.Score), 0), |
| 75 | + Timestamp: int64(z.Score), |
| 76 | + }) |
| 77 | + } |
| 78 | + |
| 79 | + return scheduledJobs, nil |
| 80 | +} |
| 81 | + |
| 82 | +// RemoveScheduledJob removes a job from the scheduled set. |
| 83 | +func (q *Queue) RemoveScheduledJob(jobId string) error { |
| 84 | + _, err := q.client.ZRem(q.ctx, q.schedulerKey, jobId).Result() |
| 85 | + if err != nil { |
| 86 | + return fmt.Errorf("failed to remove scheduled job: %w", err) |
| 87 | + } |
| 88 | + q.formatLog(LoggerInfo, "Removed scheduled job %s", jobId) |
| 89 | + return nil |
| 90 | +} |
| 91 | + |
| 92 | +// processScheduledJobs checks for jobs ready to run and moves them to the waiting list. |
| 93 | +// This method is called periodically by the scheduler loop. |
| 94 | +func (q *Queue) processScheduledJobs() { |
| 95 | + now := float64(time.Now().Unix()) |
| 96 | + |
| 97 | + // Find all jobs with score <= current timestamp |
| 98 | + results, err := q.client.ZRangeByScoreWithScores(q.ctx, q.schedulerKey, &redis.ZRangeBy{ |
| 99 | + Min: "-inf", |
| 100 | + Max: fmt.Sprintf("%f", now), |
| 101 | + }).Result() |
| 102 | + |
| 103 | + if err != nil { |
| 104 | + q.formatLog(LoggerError, "Failed to get ready scheduled jobs: %v", err) |
| 105 | + return |
| 106 | + } |
| 107 | + |
| 108 | + if len(results) == 0 { |
| 109 | + return |
| 110 | + } |
| 111 | + |
| 112 | + // Process each ready job |
| 113 | + for _, z := range results { |
| 114 | + jobId, ok := z.Member.(string) |
| 115 | + if !ok { |
| 116 | + continue |
| 117 | + } |
| 118 | + |
| 119 | + // Atomically remove from scheduled set (only one instance will succeed) |
| 120 | + removed, err := q.client.ZRem(q.ctx, q.schedulerKey, jobId).Result() |
| 121 | + if err != nil || removed == 0 { |
| 122 | + // Another instance already processed this job |
| 123 | + continue |
| 124 | + } |
| 125 | + |
| 126 | + // Add job to the queue |
| 127 | + q.AddJob(AddJobOptions{ |
| 128 | + Id: jobId, |
| 129 | + Data: nil, // Scheduled jobs don't have data in this implementation |
| 130 | + }) |
| 131 | + |
| 132 | + q.formatLog(LoggerInfo, "Moved scheduled job %s to waiting list", jobId) |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// ScheduledJobInfo contains information about a scheduled job. |
| 137 | +type ScheduledJobInfo struct { |
| 138 | + JobId string |
| 139 | + RunAt time.Time |
| 140 | + Timestamp int64 |
| 141 | +} |
0 commit comments