问题
I am working with cron in crontab for the first time and I wonder if it's possible to run something once a day at a specific time, let's say 5pm PST?
This is what I have tried but how do I base it on PST time?
0 5 * * * command
回答1:
The crontab entry will run based on the system time for the system you're running it on. If your server's time is set to Pacific Time (and note, the US is currently on Daylight Time, not Standard Time), then it will run at the specified time. If your server's time is set to some other time (such as UTC, or Eastern Time, or whatever), then you'll need to do some time zone math so that the job runs at the time you want it to run in whichever time zone you want it to run in.
Also, note that your question specifies that you want the job to run at 5pm, but your noted crontab entry of 0 5 * * *
will run at 5am in the system's time zone. If you want it to run at 5pm, the crontab entry should be 0 17 * * *
.
回答2:
cron uses 24H time, also known as military time in the US. Where 0 0 * * * is midnight and 0 12 * * * is 12 in the afternoon. You can always adapt your code if your server is in another timezone (+2 for example), to compensate from where you want the application to run.
回答3:
Quoting the crontab(5)
man page (here or type man 5 crontab
to be sure you're seeing the correct documentation for your system):
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 theTZ
environment variable in hiscrontab
this will affect only the commands executed in thecrontab
, not the execution of thecrontab
tasks themselves.
So if the system is configured to use UTC by default, time specifications in your crontab will use UTC, not local time. There's no direct way to avoid that (other than by changing the system timezone, but of course that will have other effects).
If you want your job to run at 5pm (17:00) local time, you can either schedule it for the UTC equivalent of that time (0 0 * * *
will run at midnight UTC, which is 17:00 PDT). But that won't adjust for Daylight Saving Time transitions.
Or you can schedule your job to run every hour (0 * * * *
), and then have the job itself check the local time and do nothing if the current time is not what you want. Writing a small wrapper script that invokes your command is probably the best way to do this. Don't assume that your job will run exactly on the hour. A delay of a second or so is common. For an hourly job, checking that the current time is with, say, a minute of the expected time is probably reasonable.
(This man page mentions a CRON_TZ
environment variable, but it seems to be for some implementation other than the Vixie cron used by most Linux systems.)
回答4:
Use this command:
H 5 * * *
This will set the cron to run the job at 5am PST in crontab.
来源:https://stackoverflow.com/questions/30264258/set-cron-to-run-at-5am-pst-in-crontab