Skip to content

[Linux] Use crontab to execute the program regularly

Last Updated on 2021-04-12 by Clay

Sometimes, we need to execute our program regularly, it's like crawling financial news, waking us up, and sending us emails ... etc.

In Linux, we can use crontab tool to help us set up a schedule to automatically execute programs. Today, I will simply record how to set up crontab to accomplish these functions.


crontab settings

We can use the following command to check our schedule.

crontab -l

If you output is:

no crontab for "user_name"

That mean you have no any process wait to executed.


How should we set up crontab? We can start writing with the following command:

crontab -e

If the editor for editing crontab is not familiar to you, you can use export EDITOR="EDITOR_NAME" to set the editor you want to use. For example, if you are used to using vim, then you can use export EDITOR=vim .


After starting to edit, we will see the content like this:

We need to set the five field of

  • minute (0-59)
  • hour (0-23)
  • day of month (1-31)
  • month (1-12)
  • day of week (0-6)
  • COMMAND
It's like this classic picture

And * symbol means EVERY.

For example, I have a test.sh file that I want to execute, and I want to execute it once every day at 12 o'clock in the morning, then I have to write the following command:

* 0 * * * sh /home/clay/test.sh


If I have a test.py Python program that I want to execute it every 5 minutes, then I can write:

*/5 * * * python3 /home/clay/test.py

In order to prevent errors, it is best to use the absolute path setting for the program to be executed.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version