How to set crontab every 1 hour 1 minute

大兔子大兔子 提交于 2019-12-24 09:54:08

问题


I want to schedule a command every 1 hour and 1 minute. For example, if the first command executes at 01:01 pm, the next command will execute at 01:02PM; the time between the command executions is 1 hour and 1 minute.

I tried using

*/1 */1 * * *

but it runs every minute. Can anyone help me?


回答1:


There's no way in crontab to schedule a job to run every 61 minutes (which, BTW, is an odd thing to want to do), but you can do it indirectly.

You can schedule a job to run every minute:

* * * * * wrapper_script

where wrapper_script invokes the desired command only if the current minute is a multiple of 61, something like this:

#!/bin/bash

second=$(date +%s)
minute=$((second / 60)) 
remainder=$((minute % 61))
if [[ $remainder == 0 ]] ; then
    your_command
fi

This sets $minute to the number of minutes since the Unix epoch, 1970-01-01 00:00:00 UTC. You can adjust when the command runs by using a value other than 0 in the comparison.

That's assuming you want it to run every 61 minutes (which is what you asked). But if you want to repeat in a daily cycle, so it runs at 00:00, 01:01, ..., 23:23, and then again at 00:00 the next day, you can do it directly in crontab:

 0  0 * * * your_command
 0  0 * * * your_command 
 1  1 * * * your_command 
 2  2 * * * your_command 
# ...
21 21 * * * your_command
22 22 * * * your_command 
23 23 * * * your_command



回答2:


You can use this method which tells it to run every 61 minutes after the cron job.

while true
do
  # do stuff here every 61 minutes
  sleep 61m
done

Another option:

Cron can easily run every hour, but 61 minutes is harder to achieve.

The normal methods include using a sleep command or various rather elaborate methods in the script itself to fire off every 61 minutes.

A much simpler method is using cron's cousin, the at command. The at command will run through a file and run all the commands inside, so you just need to place the commands in a file, one per line, then add this line to the bottom of the file:

at now + 61 minutes < file

The commands can be any type of one-liner you want to use.

Here is an example. Call this file foo and to kick off the execution the first time, you can simply run: sh foo

date >> ~/foo_out
cd ~/tmp && rm *
at now + 61 minutes < ~/foo

That will output the date and time to ~/foo_out then move to a tmp directory and clean out files, then tell the at command to run itself again in 61 minutes which will again run the at command after executing the rest.



来源:https://stackoverflow.com/questions/41082202/how-to-set-crontab-every-1-hour-1-minute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!