cron icon indicating copy to clipboard operation
cron copied to clipboard

Not able to pass function with parameters to AddFunc()

Open pravandkatyare opened this issue 3 years ago • 6 comments

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.

pravandkatyare avatar Mar 10 '22 05:03 pravandkatyare

You can wrap it with anonimous function if you want to pass some parameters to it.

cronInstance.AddFunc( <cronExpression>, func(func(interface{}, interface{})))

obalunenko avatar Mar 23 '22 11:03 obalunenko

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
}

electricbubble avatar Mar 23 '22 16:03 electricbubble

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

jackcipher avatar Mar 25 '22 07:03 jackcipher

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

yanqiaoyu avatar Apr 27 '22 09:04 yanqiaoyu