roylee0704 / gron

gron, Cron Jobs in Go.
MIT License
1.03k stars 62 forks source link

[feat] support cancel job. #16

Open fakeyanss opened 1 year ago

fakeyanss commented 1 year ago

Defines JobWithCancel interface. Require a unique string as jobID in each job.

Sometimes we need to cancel job after it's lifecycle finished. For example, start a monitoring job while a tcp socket alive, and cancel the monitoring job after socket closed.

So I develop the feature, support cancel job. And I defined a JobWithCancel interface, a JobID() function to index job when cancel it.

Just see this samle:

type canceledJob struct { // implements of JobWithCancel interface
    id string
}
func (j *canceledJob) JobID() {
    return id
}
func (j *canceledJob) Run() {
  fmt.Println("job run")
}
c := gron.New()
c.AddFuncWithJobID(gron.Every(1*time.Second), "job-id-1", func() {
    fmt.Println("runs every second")
})
c.AddCancelingJob(Every(1*time.Second), &canceledJob{id: "job-id-2"})
c.Start()
time.Sleep(5 * time.Second)
c.Cancel("job-id-1")
c.Cancel("job-id-2")

lastly, I using go mod in this project. I think it is compatible in higher version of golang. If you think module is not necessary, I could remove it.