You want to run a script once a day or at regular intervals.
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 |