robfig / cron

a cron library for go
MIT License
13.16k stars 1.63k forks source link

Feature request: remove a job from within the job function #472

Open myishay opened 2 years ago

myishay commented 2 years ago

I would like to be able to remove a job from within the job itself.

A workaround is welcome too :)

If you have an idea on how to implement, I would love to make the PR myself if needed.

Thank you for this amazing package!

myishay commented 2 years ago

I found a workaround!

this is how I made it:

package main

import (
    "fmt"
    "time"

    "github.com/robfig/cron/v3"
)

func main() {

    cronJob := cron.New(cron.WithLocation(time.UTC))

    var everyMinuteJobEntryID cron.EntryID
    var i int = 0
    fmt.Println("starting cron job")
    everyMinuteJobEntryID, err := cronJob.AddFunc("* * * * *", func() { // every minute
        fmt.Println("minutely job")
        i++
        if i >= 5 && everyMinuteJobEntryID != 0 {
            fmt.Println("removing minutely job")
            cronJob.Remove(everyMinuteJobEntryID)
        }
    })
    if err != nil {
        panic(err)
    }

    cronJob.Start()
    time.Sleep(10 * time.Minute)
}

The output is as follows:

$ go run main.go
starting cron job
minutely job
minutely job
minutely job
minutely job
minutely job
removing minutely job 

It might still be a good idea to implement removing a job from within the job function. @robfig WDYT?