gocron使用参数动态添加和删除任务



我在当前项目中使用gocron,并且遇到了一些文档中没有的情况。

我测试这个代码:

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)
}

当我移除任务(gocron.Remove(taskWithParams)(时,总是移除gocron.Every(3).Seconds().Do(taskWithParams,2,"world")。甚至我也交换了它们:

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

既然remove()只允许1个argument,我有没有办法具体指出我想删除哪个任务?

该文档还有一个scheduler:

s := gocron.NewScheduler()
s.Every(3).Seconds().Do(task)
<- s.Start()
  1. 什么时候是scheduler的最佳用例
  2. 如果我们已经完成了调度器,如何将其从内存中删除?scheduler.Clear()做这项工作吗?或者我们必须用另一种方法把它们从记忆中清除

您可以通过消除函数处理程序的重复来处理删除逻辑。

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)
}

否则,scheduler.Do方法将返回一个*Job的实例,您可以将该实例传递给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)
}

最新更新