在不同于服务器时区 (UTC) 的时区 (CST) 的每个午夜执行一个函数

Execute a function every midnight in a timezone (CST) different than server timezone (UTC)

我有一个时区 (timerTimeZone):例如“America/Chicago”。

让 timerTimeZone = "America/Chicago"

我们的服务器本地时间是 UTC。

我想在存储在 timerTimeZone 变量中的时区每晚中午 12 点执行一个函数。

假设节目是 运行 下午 6:00 UTC/1.00 PM CST。所以第一次执行应该在 11 小时后(中部标准时间上午 12 点),接下来的后续执行每 24 小时一次。

我一直在尝试使用 moment 和 moment-timezone 但找不到任何方法。

我建议使用优秀的 Cron 模块。

这允许您根据 cron 表达式安排任务,还允许您指定要使用的 IANA 时区。

我还在这里记录了接下来的 5 个工作日期运行,都在指定的时区和 UTC。

const CronJob = require("cron").CronJob;

// Run at midnight every night
const cronExpression = "00 00 * * *";

const timeZone = "America/Chicago";

const cronJob = new CronJob(
    cronExpression,
    cronFunction,
    null,
    true,
    timeZone
);

function cronFunction() {
    console.log("cronFunction: Running....");
    /* Do whatever you wish here... */
}

// Get the next N dates the job will fire on...
const nextDates = cronJob.nextDates(5);
console.log(`Next times (${timeZone}) the job will run on:`, nextDates.map(d => d.tz(timeZone).format("YYYY-MM-DD HH:mm")));
console.log("Next times (UTC) the job will run on:", nextDates.map(d => d.utc().format("YYYY-MM-DD HH:mm")));