Question 3.21: You want to run a script once a day or at regular intervals....

You want to run a script once a day or at regular intervals.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the Linux crontab command.

To do this, the Raspberry Pi needs to know the time and date, and therefore needs a network connection or a real-time clock. See Recipe 11.13.

Discussion

The command crontab allows you to schedule events to take place at regular intervals. This can be daily or hourly, and you can even define complicated patterns so different things happen on different days of the week. This is useful for backup tasks that you might want to run in the middle of the night.

You can edit the scheduled events using the following command:

$ crontab -e

If the script or program that you want to run needs to be run by a superuser, then prefix all the crontab commands with sudo (Recipe 3.11).

The comment line indicates the format of a crontab line. The digits are, in order, minute, hour, day of month, month, day of week, and then the command that you want to run.

If there is a * in the digit position, that means every; if there is a number there instead, the script will only be run at that minute/hour/day of the month.

So, to run the script every day at 1 a.m., you would add the line shown in Figure 3-7.

Using only a single digit, you can specify ranges to run the script just on weekdays; for example:

0 1 * * 1-5 /home/pi/myscript.sh

If your script needs to be run from a particular directory, you can use a semicolon (;) to separate multiple commands as shown here:

0 1 * * * cd /home/pi; python mypythoncode.py

See Also

You can see the full documentation for crontab by entering this command:

$ man crontab
7

Related Answered Questions

Question: 3.34

Verified Answer:

Use the Linux df command: $ df -h Filesystem   ...
Question: 3.33

Verified Answer:

Use the Linux date command. The date and time form...
Question: 3.32

Verified Answer:

Edit the file ~/.bashrc using nano (Recipe 3.6), a...
Question: 3.31

Verified Answer:

Run the program or command in the background using...
Question: 3.30

Verified Answer:

Redirect the output to /dev/null using >. For e...
Question: 3.24

Verified Answer:

Use the Task Manager utility, which you’ll find on...
Question: 3.29

Verified Answer:

Use the pipe command, which is the bar symbol (|) ...
Question: 3.27

Verified Answer:

Use the > command to redirect output that would...
Question: 3.28

Verified Answer:

Use the cat command to concatenate a number of fil...
Question: 3.26

Verified Answer:

Use the lsusb command. This will list all the devi...