With github.com/robfig/cron/v3 You can use Cron.Entry.
This is a basic usage example:
job := cron.FuncJob(func() {
fmt.Println("Hello Cron")
})
c := cron.New(/* options */)
entryId := c.Schedule(cron.Every(time.Second*5), job)
// Find the job entry
entry := c.Entry(entryId)
// ... here you can inspect the job `entry`
// Removes the entry, it won't run again
c.Remove(entryId)
cron.FuncJob is actually just a wrapper around func(). In case you need more complex behavior, or state, you can implement the Job interface yourself:
type myJob struct{}
func (j *myJob) Run() {
fmt.Println("foo")
}
Then you can fetch the specific instance of your job by type-asserting:
j := c.Entry(id).Job.(*myJob)
// ... do something with the *myJob instance
You can also customize the schedule, by implementing Schedule interface:
type mySchedule struct{}
// Next returns the next activation time, later than the given time.
// Next is invoked initially, and then each time the job is run.
func (s *mySchedule) Next(time.Time) time.Time {
return time.Now().Add(time.Second*5)
}
And then use it all like:
c := cron.New(/* options */)
entryId := c.Schedule(&mySchedule{}, &myJob{})
If you use an earlier version of the package, unfortunately you can't get a single entry by id and Cron.Schedule doesn't assign ids either. You must manage a lookup table yourself. If possible, I recommend upgrading to v3.