如何使用gocraft将时区传递给cron表达式?

huangapple go评论118阅读模式
英文:

How to pass timezone to cron expression using gocraft?

问题

我正在使用github.com/gocraft/work来创建cron作业。我的服务器时间是UTC,我希望基于特定时区执行cron作业,是否有办法在gocraft worker中指定带有时区的cron表达式。

  1. // 代码在这里
  2. pool := work.NewWorkerPool(Context{}, 10, "test_namespace", redisPool)
  3. pool.PeriodicallyEnqueue("0 30 10 * * *", "export") // 每天上午10:30运行
  4. pool.Job("export", jobsHandler.SendExportReport)
  5. // 开始处理作业
  6. pool.Start()
  7. // 等待退出信号:
  8. signalChan := make(chan os.Signal, 1)
  9. signal.Notify(signalChan, os.Interrupt, os.Kill)
  10. <-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 -->

  1. // Code here
  2. pool := work.NewWorkerPool(Context{}, 10, &quot;test_namespace&quot;, redisPool)
  3. pool.PeriodicallyEnqueue(&quot;0 30 10 * * *&quot;, &quot;export&quot;) // Runs at 10:30am everyday
  4. pool.Job(&quot;export&quot;, jobsHandler.SendExportReport)
  5. // Start processing jobs
  6. pool.Start()
  7. // Wait for a signal to quit:
  8. signalChan := make(chan os.Signal, 1)
  9. signal.Notify(signalChan, os.Interrupt, os.Kill)
  10. &lt;-signalChan

<!-- end snippet -->

答案1

得分: 1

由于您使用的软件包期望 cron 时间以服务器的本地时间(UTC)表示,并且您有一个特定的时区输入,所以可以将本地时间(时区)转换为 UTC:

  1. nyc, err := time.LoadLocation("America/New_York")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. // 12:15:23 -0400 EDT
  6. localTime := time.Date(
  7. 2022, 5, 13, // date (ignored below)
  8. 12, // hour
  9. 15, // minute
  10. 23, // seconds,
  11. 0, // ns
  12. nyc, // tz
  13. )
  14. // tz Time in UTC
  15. h, m, s := localTime.UTC().Clock() // 16 15 23
  16. 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:

  1. nyc, err := time.LoadLocation(&quot;America/New_York&quot;)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. // 12:15:23 -0400 EDT
  6. localTime := time.Date(
  7. 2022, 5, 13, // date (ignored below)
  8. 12, // hour
  9. 15, // minute
  10. 23, // seconds,
  11. 0, // ns
  12. nyc, // tz
  13. )
  14. // tz Time in UTC
  15. h, m, s := localTime.UTC().Clock() // 16 15 23
  16. cronTime := fmt.Sprintf(&quot;%d %d %d * * *&quot;, s, m, h) // 23 15 16 * * *

https://go.dev/play/p/QdpoLsDiPwR

huangapple
  • 本文由 发表于 2022年5月13日 19:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/72228552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定