Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: activate/deactivate job #386

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ type Entry struct {
// Prev is the last time this job was run, or the zero time if never.
Prev time.Time

// Activate determines whether to skip Job execution.
Activate bool

// WrappedJob is the thing to run when the Schedule is activated.
WrappedJob Job

Expand Down Expand Up @@ -164,6 +167,7 @@ func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID {
Schedule: schedule,
WrappedJob: c.chain.Then(cmd),
Job: cmd,
Activate: true,
}
if !c.running {
c.entries = append(c.entries, entry)
Expand Down Expand Up @@ -211,6 +215,18 @@ func (c *Cron) Remove(id EntryID) {
}
}

// Activate an entry to enable it's execution.
func (c *Cron) Activate(id EntryID) {
c.setEntryActivate(id, true)
c.logger.Info("activate", "entry", id)
}

// Deactivate an entry to prevent it's execution.
func (c *Cron) Deactivate(id EntryID) {
c.setEntryActivate(id, false)
c.logger.Info("deactivate", "entry", id)
}

// Start the cron scheduler in its own goroutine, or no-op if already started.
func (c *Cron) Start() {
c.runningMu.Lock()
Expand Down Expand Up @@ -267,7 +283,7 @@ func (c *Cron) run() {

// Run every entry whose next time was less than now
for _, e := range c.entries {
if e.Next.After(now) || e.Next.IsZero() {
if e.Next.After(now) || e.Next.IsZero() || !e.Activate {
break
}
c.startJob(e.WrappedJob)
Expand Down Expand Up @@ -353,3 +369,12 @@ func (c *Cron) removeEntry(id EntryID) {
}
c.entries = entries
}

func (c *Cron) setEntryActivate(id EntryID, activate bool) {
for _, e := range c.entries {
if e.ID == id {
e.Activate = activate
return
}
}
}