robfig / cron

a cron library for go
MIT License
13.1k stars 1.62k forks source link

Not able to pass function with parameters to AddFunc() #443

Open pravandkatyare opened 2 years ago

pravandkatyare commented 2 years ago

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.

obalunenko commented 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{})))

electricbubble commented 2 years ago
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
}
jackcipher commented 2 years ago

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

yanqiaoyu commented 2 years ago

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 {}
}
mesameen commented 9 months ago

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 ?

liguoqinjim commented 8 months ago

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