Open pravandkatyare opened 2 years ago
You can wrap it with anonimous function if you want to pass some parameters to it.
cronInstance.AddFunc( <cronExpression>, func(func(interface{}, interface{})))
var _ cron.Job = (*tmpJob)(nil)
type tmpJob struct {
name string
done chan struct{}
}
func (t *tmpJob) Run() {
fmt.Println("hi", t.name)
t.done <- struct{}{}
}
func TestCronJob(t *testing.T) {
c := cron.New(cron.WithSeconds())
c.Start()
job := &tmpJob{
name: "electricbubble",
done: make(chan struct{}),
}
_, err := c.AddJob("* * * * * *", job)
if err != nil {
t.Fatal(err)
}
<-job.done
}
In actual, AddFunc is just a wrapper for AddJob. AddJob will be invoked finnaly.
So, If u wanna carry some params, u can use AddJob(), as @electricbubble provieds
this is how I solve it by using AddFunc
package main
import (
"log"
"github.com/robfig/cron/v3"
)
func showName(name string) {
log.Println("Hi~ My name is", name)
}
func main() {
c := cron.New(cron.WithSeconds())
c.AddFunc("*/1 * * * * ?", func() { showName("Johnny Silverhand") })
c.AddFunc("*/1 * * * * ?", func() { showName("V") })
c.Start()
select {}
}
this is how I solve it by using AddFunc
package main import ( "log" "github.com/robfig/cron/v3" ) func showName(name string) { log.Println("Hi~ My name is", name) } func main() { c := cron.New(cron.WithSeconds()) c.AddFunc("*/1 * * * * ?", func() { showName("Johnny Silverhand") }) c.AddFunc("*/1 * * * * ?", func() { showName("V") }) c.Start() select {} }
How to pass function params to remember like spawning AddFunc in a loop @yanqiaoyu ?
@mesameen maybe like this
package main
import (
"log"
"github.com/robfig/cron/v3"
)
func showName(name string) {
log.Println("Hi~ My name is", name)
}
func main() {
c := cron.New(cron.WithSeconds())
names := []string{"Johnny Silverhand", "V"}
for _, name := range names {
c.AddFunc("*/1 * * * * ?", func(n string) func() {
return func() {
showName(n)
}
}(name))
}
c.Start()
select {}
}
I wanted to pass some of the data which is essential for a cron job for execution of internal logic.
Lets take an example as
cronInstance.AddFunc( <cronExpression>, func(interface{}, interface{}))
which as of now I'm not able to do.If not this way, please suggest me some alternative to pass data to cron job while it is being added to run.