gocroncallback

Get scheduled time of current cronjob task inside scheduled function


I want to access the scheduled time of the current task inside the scheduled function.

I have attempted in https://go.dev/play/:

package main

import (
    "fmt"
    "time"

    "github.com/go-co-op/gocron/v2"
)

func main() {
    s, _ := gocron.NewScheduler()
    defer func() {
        _ = s.Shutdown()
    }()

    var j gocron.Job
    j, _ = s.NewJob(
        gocron.DurationJob(
            time.Second,
        ),
        gocron.NewTask(
            func() {
                fmt.Println(j.LastRun())
            },
        ),
    )
    s.Start()
    select {}
}

However, the printout is

timeout running program
0001-01-01 00:00:00 +0000 UTC gocron: job not found
0001-01-01 00:00:00 +0000 UTC gocron: job not found
0001-01-01 00:00:00 +0000 UTC gocron: job not found
0001-01-01 00:00:00 +0000 UTC gocron: job not found
...

Moreover, I'm not sure if this is the proper way to fetch the scheduled time of the current run.


Solution

  • This has been fixed in releases since Feb 2024. If you are still having an issue with it, please open an issue on the repo!

    Using the playground link from markus-w-mahlberg -> run on playground

    Logs

    2009/11/10 23:00:01 main.main.func2 doing stuff
    2009/11/10 23:00:01 Inside task last run: 2009-11-10 23:00:01 +0000 UTC
    2009/11/10 23:00:02 main.main.func2 doing stuff
    2009/11/10 23:00:02 Inside task last run: 2009-11-10 23:00:02 +0000 UTC
    2009/11/10 23:00:02 Last run: 2009-11-10 23:00:02 +0000 UTC
    2009/11/10 23:00:03 main.main.func2 doing stuff
    2009/11/10 23:00:03 Inside task last run: 2009-11-10 23:00:03 +0000 UTC
    2009/11/10 23:00:04 Last run: 2009-11-10 23:00:03 +0000 UTC
    2009/11/10 23:00:04 main.main.func2 doing stuff
    2009/11/10 23:00:04 Inside task last run: 2009-11-10 23:00:04 +0000 UTC
    2009/11/10 23:00:05 main.main.func2 doing stuff
    2009/11/10 23:00:05 Inside task last run: 2009-11-10 23:00:05 +0000 UTC
    2009/11/10 23:00:06 main.main.func2 doing stuff
    2009/11/10 23:00:06 Last run: 2009-11-10 23:00:06 +0000 UTC
    2009/11/10 23:00:06 Inside task last run: 2009-11-10 23:00:06 +0000 UTC
    2009/11/10 23:00:07 main.main.func2 doing stuff
    2009/11/10 23:00:07 Inside task last run: 2009-11-10 23:00:07 +0000 UTC
    2009/11/10 23:00:08 Last run: 2009-11-10 23:00:07 +0000 UTC
    2009/11/10 23:00:08 main.main.func2 doing stuff
    2009/11/10 23:00:08 Inside task last run: 2009-11-10 23:00:08 +0000 UTC
    2009/11/10 23:00:09 main.main.func2 doing stuff
    2009/11/10 23:00:09 Inside task last run: 2009-11-10 23:00:09 +0000 UTC
    2009/11/10 23:00:10 Shutting down...
    2009/11/10 23:00:10 main.main.func2 doing stuff
    timeout running program