更改 cronjob 的时区

更改 cronjob 的时区

我有一个 cronjob,每天在 UTC 时间上午 9:00 执行。我现在处于 GMT+1,因此它在当地时间上午 10:00 执行。当时区发生更改(改为夏令时,DST)时,cronjob 仍会在 UTC 时间上午 9:00 执行,但会在当地时间上午 11:00 执行。但我希望它始终在 10:00 执行,无论夏令时与否。我怎么做?

答案1

这可能取决于您的操作系统及其cron.这在最流行的 cron 实现中是不可能的vixie/isc cron。来自crontab(5) manpage

LIMITATIONS
       The  cron  daemon  runs with a defined timezone. It currently does not 
       support per-user timezones. All the tasks: system's and user's will 
       be run based on the configured timezone. Even if a user specifies  
       the TZ  environment  variable  in  his crontab this will affect only 
       the commands executed in the crontab, not the execution of the crontab 
       tasks themselves.

答案2

扩展@Cyrus 的答案,这就是我所做的:

我制作了一个检查 UTC 偏移量的脚本:

#!/bin/bash
export TZ=":US/Eastern"
if [ "$(date +%z)" == "$1" ]; then
  shift
  exec $@
fi

然后我为我想要的偏移量添加两个 crontab 条目:

0 8 * * * run-only-with-tz.sh -0400 place_your_command_here
0 9 * * * run-only-with-tz.sh -0500 place_your_command_here

答案3

检查 /etc/timezone 中的设置。在您提到的问题中,您所在的位置是“GMT+1”,如果您的时区设置为“GMT+1”,那么您的脚本将始终在 UTC 加一小时执行。如果设置为例如“欧洲/巴黎”,则执行时间将随着夏令时而变化。

答案4

从手册页:

/etc/timezone守护进程将使用时区的定义(如果存在) 。

可以在用户的​​ crontab 定义中重新定义环境,但 cron 只能处理单个时区的任务。

相关内容