英文:
How to pass timezone to cron expression using gocraft?
问题
我正在使用github.com/gocraft/work来创建cron作业。我的服务器时间是UTC,我希望基于特定时区执行cron作业,是否有办法在gocraft worker中指定带有时区的cron表达式。
// 代码在这里
pool := work.NewWorkerPool(Context{}, 10, "test_namespace", redisPool)
pool.PeriodicallyEnqueue("0 30 10 * * *", "export") // 每天上午10:30运行
pool.Job("export", jobsHandler.SendExportReport)
// 开始处理作业
pool.Start()
// 等待退出信号:
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, os.Kill)
<-signalChan
英文:
I am using github.com/gocraft/work for creating cron jobs. My server time is in UTC and I want cron job to be executed based on specific timezone, is there any way to specify cron expression with timezone in gocraft worker.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
// Code here
pool := work.NewWorkerPool(Context{}, 10, "test_namespace", redisPool)
pool.PeriodicallyEnqueue("0 30 10 * * *", "export") // Runs at 10:30am everyday
pool.Job("export", jobsHandler.SendExportReport)
// Start processing jobs
pool.Start()
// Wait for a signal to quit:
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, os.Kill)
<-signalChan
<!-- end snippet -->
答案1
得分: 1
由于您使用的软件包期望 cron 时间以服务器的本地时间(UTC)表示,并且您有一个特定的时区输入,所以可以将本地时间(时区)转换为 UTC:
nyc, err := time.LoadLocation("America/New_York")
if err != nil {
log.Fatal(err)
}
// 12:15:23 -0400 EDT
localTime := time.Date(
2022, 5, 13, // date (ignored below)
12, // hour
15, // minute
23, // seconds,
0, // ns
nyc, // tz
)
// tz Time in UTC
h, m, s := localTime.UTC().Clock() // 16 15 23
cronTime := fmt.Sprintf("%d %d %d * * *", s, m, h) // 23 15 16 * * *
您可以在此链接中查看代码示例:https://go.dev/play/p/QdpoLsDiPwR
英文:
Since the package you are using is expecting the cron time in the local time of the server (UTC) and you have a specific timezone input - simple convert your local (TZ) time to UTC:
nyc, err := time.LoadLocation("America/New_York")
if err != nil {
log.Fatal(err)
}
// 12:15:23 -0400 EDT
localTime := time.Date(
2022, 5, 13, // date (ignored below)
12, // hour
15, // minute
23, // seconds,
0, // ns
nyc, // tz
)
// tz Time in UTC
h, m, s := localTime.UTC().Clock() // 16 15 23
cronTime := fmt.Sprintf("%d %d %d * * *", s, m, h) // 23 15 16 * * *
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论