In Linux, schedule task to Hour, minute, second pr

2020-03-05 06:17发布

问题:

I just want to run a shell scrip at say this exact time "16:22:36". utilities like "at" are useless since they don't have "seconds". "sleep" does not work since the loop is ending 8 hours ahead of time for some reason :s , I have searched all over google and couldn't find any tools. so a huge Os like Linux doesn't have a proper task scheduler?

回答1:

The standard cron lacks second precision scheduling because

  1. Unix server administration traditionally rarely needed one-second precision
  2. It might be used in such a disturbing way for a multi-user system like "Run this task every second"

However with the help of sleep(1) from GNU Coreutils suite, you can achieve true second precision job scheduling.

Example: wait for 12:14:05 and 12:14:10

$ crontab -l
(snip...)
14 12 * * * sleep 5; date > /tmp/plain.txt
14 12 * * * while [ "1410" -gt "$(date +\%M\%S)" ]; do /bin/sleep 0.1; done; date > /tmp/while.txt

(wait for a while...)

$ ls -l --time-style=full-iso /tmp/*.txt
-rw-r--r-- 1 nodakai nodakai 43 2014-02-22 12:14:06.236151567 +0800 /tmp/plain.txt
-rw-r--r-- 1 nodakai nodakai 43 2014-02-22 12:14:10.007600677 +0800 /tmp/while.txt

As you see from the 1st version, 14 12 in crontab does not guarantee 12:14:00 sharp. The 2nd version uses while loop and sub-second sleep(1) to achieve sub-second precision.

Note that, unless you use NTP to synchronize your machine clock to time servers, it is meaningless to talk about second precision job scheduling.



回答2:

You could create a crontab entry for the hour and minute with a sleep of 36 seconds

22 16 * * * sleep 36; shell_script.sh


回答3:

Linux has a wonderful task scheduler, called crontab. There is a wealth of info about it on the web. As a simple "this is what it does and how to use it" though: http://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/ - Should get you started.