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

Added a way to update an exising entry #183

Closed
wants to merge 1 commit into from
Closed
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
24 changes: 24 additions & 0 deletions cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type Cron struct {
entries []*Entry
stop chan struct{}
add chan *Entry
update chan *Entry
remove chan EntryID
snapshot chan []Entry
running bool
Expand Down Expand Up @@ -104,6 +105,7 @@ func New(opts ...Option) *Cron {
add: make(chan *Entry),
stop: make(chan struct{}),
snapshot: make(chan []Entry),
update: make(chan *Entry),
remove: make(chan EntryID),
running: false,
logger: log.New(os.Stderr, "", log.LstdFlags),
Expand Down Expand Up @@ -179,6 +181,15 @@ func (c *Cron) Entry(id EntryID) Entry {
return Entry{}
}

// Update an already exising entry, entry.ID should be set to a valid ID
func (c *Cron) Update(entry *Entry) {
if c.running {
c.update <- entry
} else {
c.updateEntry(entry)
}
}

// Remove an entry from being run in the future.
func (c *Cron) Remove(id EntryID) {
if c.running {
Expand Down Expand Up @@ -254,6 +265,10 @@ func (c *Cron) run() {
e.Next = e.Schedule.Next(now)
}

case e := <-c.update:
timer.Stop()
c.updateEntry(e)

case newEntry := <-c.add:
timer.Stop()
now = c.now()
Expand Down Expand Up @@ -306,6 +321,15 @@ func (c *Cron) entrySnapshot() []Entry {
return entries
}

func (c *Cron) updateEntry(new *Entry) {
for _, entry := range c.entries {
if new.ID == entry.ID {
*entry = *new
return
}
}
}

func (c *Cron) removeEntry(id EntryID) {
var entries []*Entry
for _, e := range c.entries {
Expand Down