Search code examples
gocron

gocron to add and remove task dynamically with parameter


I am using gocron in my current project and I had encounter a few situations that not in the document.

I test this code:

gocron.Every(3).Seconds().Do(taskWithParams,2,"world")
gocron.Every(2).Seconds().Do(taskWithParams,1, "hello")
gocron.Start()

time.Sleep(10 * time.Second)
gocron.Remove(taskWithParams)//<-- remove task
...

func taskWithParams(a int, b string) {
    fmt.Println(a, b)
}

When I remove task(gocron.Remove(taskWithParams)), always gocron.Every(3).Seconds().Do(taskWithParams,2,"world") is removed. even I swap them:

gocron.Every(2).Seconds().Do(taskWithParams,1, "hello")
gocron.Every(3).Seconds().Do(taskWithParams,2,"world")

Is there a way for me to specifically point out which task I want to remove, since the remove() only allow 1 argument?

The document also have a scheduler:

s := gocron.NewScheduler()
    s.Every(3).Seconds().Do(task)
    <- s.Start()
  1. When is the best use case for scheduler?
  2. If we are done with scheduler, how to remove it from memory? do scheduler.Clear() does the job? or we have to have another way to clear them from the memory?

Solution

  • you can handle the removal logic by deduplicating the function handlers.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        fn1 := func() { taskWithParams(2, "world") }
        gocron.Every(3).Seconds().Do(fn1)
        fn2 := func() { taskWithParams(1, "hello") }
        gocron.Every(2).Seconds().Do(fn2)
        gocron.Start()
    
        time.Sleep(10 * time.Second)
        gocron.Remove(fn2)
    }
    func taskWithParams(a int, b string) {
        fmt.Println(a, b)
    }
    

    Otherwise, the scheduler.Do method returns an instance of *Job that you can pass to scheduler.RemoveByReference.

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        job, err := gocron.Every(3).Seconds().Do(taskWithParams, 2, "ww")
        if err != nil {
            panic(err)
        }
        gocron.Every(2).Seconds().Do(taskWithParams, 1, "hh")
        gocron.Start()
    
        time.Sleep(10 * time.Second)
        gocron.RemoveByReference(job)
    }
    func taskWithParams(a int, b string) {
        fmt.Println(a, b)
    }