Two methods for crontab implementation to execute scripts every several days



In our work, we often encounter the situation of how many days / hours / minutes to execute a script or a command. If the program is run every hour and every minute, it may be easier to implement in crontab. Here are some examples and the format description of crontab:

Specific examples:

#Script every 15 minutes from 6pm to 6am
0,15,30,45 18-06 * * * /bin/bash $HOME/ > /dev/null 2>&1
#Every two hours, restart the service
* */2 * * * /etc/init.d/apache2 restart

Here is a summary of crontab every minute, every hour, every day / week / month / year

  • Every five minutes * / 5 * **
  • 0 * / 5 * every five hours*
  • 0 0 * per day*
  • Execute 0 0 * 0 every week
  • 0 0 1 * per month*
  • 0 0 1 1 per year*

If a script is executed every 10 days every month, it can also be written as:

#On the 1st, 11th, 21st and 31st of each month, perform HTTP service restart
0 0 */10 * * /etc/init.d/apache2 restart

But if the script is executed according to the natural days, for example, every 27 days, how can it be implemented? In this case, it can’t be directly implemented through crontab, so it must be implemented by detour.

Here are two ways to think about it.

[method 1] control time by script

Train of thought:

1) Set the number of times to execute in the script Here, if 10 times, the interval is 27 days, is the script to execute

2) Then executenohup bash &Put it in the background for automatic execution

[method 2] indirect implementation through crontab

Train of thought:

1) Execute the script regularly every day, and then judge in the script. When the interval meets the conditions

2) Execute the and modify the last execution time to facilitate the next execution


The above is the whole content of this article. I hope that the content of this article can bring some help to your study or work. If you have any questions, you can leave a message and communicate with us. Thank you for your support for developpaer.