How can I write a Crontab that will run my /home/username/test.sh
script every 2 hours?
6 Answers
Just do:
0 */2 * * * /home/username/test.sh
The 0 at the beginning means to run at the 0th minute. (If it were an *, the script would run every minute during every second hour.)
Don't forget, you can check syslog to see if it ever actually ran!
-
@ernest-conill How can you tell? the revisions history does not contain a version which includes different code: stackoverflow.com/posts/6423532/revisions Commented Aug 31, 2014 at 11:55
-
As I understand the cron syntax, this answer is not quite correct. You were asked for an execution every two hours, your argument fulfils this requirement in principle, but it depends on the minute of the hour. Your argument is executed at 00:00, 02:00, 04:00, 06:00 and so on. If the server is restarted at 03:58 and takes until 04:02, the execution at 04:00 is omitted. In my opinion, it would be better to use */120 * * * * *– MaxWebCommented Feb 9, 2023 at 12:13
-
I was probably a bit hasty here :D */120 is not a valid option. However, the original statement remains the same. 0 */2 * * can cause an execution to be skipped. However, I probably don't have an alternative after all, unfortunately.– MaxWebCommented Feb 9, 2023 at 12:47
The line should read either:
0 0-23/2 * * * /home/username/test.sh
or
0 0,2,4,6,8,10,12,14,16,18,20,22 * * * /home/username/test.sh
-
3"0-23/2" -- between the hours 0 and 23 run every 2 hours. Commented Nov 24, 2016 at 10:38
-
-
2
-
-
2if your cron supports it,
0-23/2
is every even hour and1-23/2
is every odd hour, but I'd prefer*/2
still.– BetlistaCommented May 25, 2020 at 7:27
0 */2 * * *
The answer is from https://crontab.guru/every-2-hours. It is interesting.
0 */1 * * * “At minute 0 past every hour.”
0 */2 * * * “At minute 0 past every 2nd hour.”
This is the proper way to set cronjobs for every hr.
To Enter into crontab :
crontab -e
write this into the file:
0 */2 * * * python/php/java yourfilepath
Example :0 */2 * * * python ec2-user/home/demo.py
and make sure you have keep one blank line after the last cron job in your crontab file
first do crontab -l to see your existing crontab and jobs if you don't anything then do crontab -e
check you editor maybe VI or nano or anything like that.. go to insert mode by 'i', command should be like (cron expression)[space](program execution address from home)[space](your script address from home)
example (0 /2 * * * /conda///bin/python3 ///USERNAME/TEST_PYTHON_SCRIPT.py >> execution_log.txt)
execution_log.txt will have the execution log of your script.
once you have your command correctly placed exit the editor by saving the file for nano -> ctrl + x for vi -> :wq!
check your scripts with some email/print statement.