Add registers a single cron job. If there is already a job with the provided id, then the old job will be replaced with the new one. cronExpr is a regular cron expression, eg. "0 */3 * * *" (aka. at minute 0 past every 3rd hour). Check cron.NewSchedule() for the supported tokens.
(jobId string, cronExpr string, fn func())
| 81 | // cronExpr is a regular cron expression, eg. "0 */3 * * *" (aka. at minute 0 past every 3rd hour). |
| 82 | // Check cron.NewSchedule() for the supported tokens. |
| 83 | func (c *Cron) Add(jobId string, cronExpr string, fn func()) error { |
| 84 | if fn == nil { |
| 85 | return errors.New("failed to add new cron job: fn must be non-nil function") |
| 86 | } |
| 87 | |
| 88 | schedule, err := NewSchedule(cronExpr) |
| 89 | if err != nil { |
| 90 | return fmt.Errorf("failed to add new cron job: %w", err) |
| 91 | } |
| 92 | |
| 93 | c.mux.Lock() |
| 94 | defer c.mux.Unlock() |
| 95 | |
| 96 | // remove previous (if any) |
| 97 | c.jobs = slices.DeleteFunc(c.jobs, func(j *Job) bool { |
| 98 | return j.Id() == jobId |
| 99 | }) |
| 100 | |
| 101 | // add new |
| 102 | c.jobs = append(c.jobs, &Job{ |
| 103 | id: jobId, |
| 104 | fn: fn, |
| 105 | schedule: schedule, |
| 106 | }) |
| 107 | |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | // Remove removes a single cron job by its id. |
| 112 | func (c *Cron) Remove(jobId string) { |