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

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

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, &quot;test_namespace&quot;, redisPool)
	pool.PeriodicallyEnqueue(&quot;0 30 10 * * *&quot;, &quot;export&quot;) // Runs at 10:30am everyday
	pool.Job(&quot;export&quot;, 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)
	&lt;-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(&quot;America/New_York&quot;)
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(&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:

确定