How to use cron scheduled tasks for planning work on Ubuntu?

Cron is a built-in scheduling tool in Ubuntu that allows you to schedule tasks to run automatically at specified times and dates. Here are the steps to set up cron jobs in Ubuntu:

Open the terminal: Press Ctrl+Alt+T or search for “Terminal” in the Ubuntu launcher.

Check the cron service status: Run the following command in the terminal to see if the cron service is running or not:

sudo service cron status

Install or update cron: Use the following command to install cron if it is not already installed or to update if it is outdated:

sudo apt-get install cron

Edit crontab: Once you have installed cron, you can edit the crontab file to specify the tasks that need to be scheduled. Use the following command to edit the crontab file:

1
crontab -e

This will open the crontab file in the default text editor. The syntax for specifying a cron job is as follows:

1
2
3
4
5
6
7
8
* * * * * /path/to/command
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday is both 0 and 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Add a cron job: Once you have opened the crontab file, you can add a new line to schedule a task. For example, if you want to run a script named myscript.sh every day at 10:30 AM, you can add the following line:

1
30 10 * * * /path/to/myscript.sh

Here, 30 specifies the minute, 10 specifies the hour, and * * * specifies that the task should run every day of every month.

Save and exit: Once you have added the cron job, save and exit the crontab file.

Verify the output: To check the output of the scheduled tasks, you can redirect the output to a log file. For example, you can modify the cron job in step 5 as follows:

1
30 10 * * * /path/to/myscript.sh >> /path/to/logfile.log 2>&1

Here, >> appends the output to the log file, and 2>&1 redirects any error messages to the same log file.

That’s it! You have successfully set up a cron job in Ubuntu to schedule a task. You can use cron to automate many repetitive tasks, such as backups, system updates, and running scripts.