Want to run a command or a script daily, weekly, monthly, or on other given schedule? It’s easy to do this in Ubuntu via cron job.
Cron is a time-based job scheduler to run command or script periodically at fixed times, dates, or intervals. It’s typically used for system maintenance or administration, though it can be useful for general purpose, e.g., downloading file from internet at regular intervals.
1. Edit crontab files:
Users can set up a cron job easily by configuring crontab file by crontab command. It’s pre-installed in Ubuntu based systems. And each user has its own crontab config file.
b.) Schedule task for current user:
To run command or script by current user, simply open terminal from system app launcher and run command:
For the first time, it will prompt to select an editor to edit the config file. Choose one you prefer or press Enter to use the default nano text editor.
b.) If need root or sudo privilege:
For command or script need sudo or root user privilege, you may run following command instead:
sudo crontab -e
It will create (if not exit) or open the configuration file for root user.
c.) Specify a user to run the schedule task:
You can add
-u <user_name> flag to specify the user, ji for instance.
sudo crontab -u ji -e
User can be root, so it will do the same to
sudo crontab -e:
sudo crontab -u root -e
2. Set time interval, command or script to run periodically:
After running a command in step 1, it opens the configuration file in the terminal window (or command console).
Now scroll down and add a new line:
* * * * * <command or script>
The first 5 asterisks “*” specify the time and date, change them accordingly.
a.) For example, to run a python3 script under my Documents folder at midnight (00:00) every Sunday, use:
0 0 * * 0 python3 /home/ji/Documents/script.py
- the first 0 specifies the minute, use * for every minute.
- the second 0 specifies the hour, use * for every hour.
- the third flag * specifies the day of month, every day if week day not specified.
- the forth flag * says every month.
- the fifth flag (third 0) specifies the week day. From 0 to 6 mean Sunday to Saturday.
echo "hello world!" command everyday at 16:30, add this line:
30 16 * * * echo "hello world!"
c.) You can use
*/n to run for every n-th interval of time. And use multiple specific time intervals with commas.
For instance, run the command every Friday at first, second, an third hour every 5th minute (01:00, 01:05, 01:10, …, 02:00, 02:05, 02:10, …, 03:55).
*/5 1,2,3 * * 5 echo "hello world!"
Finally, save the configuration file. If edited via nano, press Ctrl+X on keyboard, type y, and hit Enter to save it.
I am new to Linux Systems Administration. Are there anymore tips you are able to pass along to me.