cron icon indicating copy to clipboard operation
cron copied to clipboard

Feature request: remove a job from within the job function

Open myishay opened this issue 3 years ago • 2 comments

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 avatar Nov 29 '22 12:11 myishay

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?

myishay avatar Nov 29 '22 15:11 myishay