How to Setup Cron Job in Ubuntu

In Ubuntu you can easily schedule tasks using Cron tool. It is a time-based job scheduling daemon that runs in the background. The scheduled operations or jobs are called as Cron jobs. crontab is the file that lists the jobs.

Install Cron on Ubuntu

Ubuntu comes with cron installed by default. If you don’t have then you can install it using below command.

sudo apt install cron

Then enable it using below command to run in background.

sudo systemctl enable cron

Now your system ready for you to start scheduling jobs.

Edit Crontab File in Ubuntu

You can edit the crontab file using below command. Your cron jobs are managed in this file.

crontab -e

If this is the first time you’re running the crontab command, then it will prompt you to select a default text editor. Just select 1 and enter to edit the file with nano text editor.In the future, it will open your crontab in this text editor automatically.

Crontab File

Tasks scheduled in a crontab are structured like below

minute hour day_of_month month day_of_week command_to_run

Example:
For example, you can run a backup of all your user accounts at 6 a.m every week with. Not just this command, you can run any command, script or file.

0 6 * * 1 tar -zcf /var/backups/home.tgz /home/

Edit Crontab File

After that press Ctrl + X on your keyboard. Now enter Y and hit the enter key.Again hit the Enter key. This will Save and close the file.

Also Read:  How to Check System Uptime on Ubuntu Linux

minute: 0-59
hour: 0-23
Day of the month: 1-31
month: 1-12 or JAN-DEC
Day of the week: 0-6 or SUN-SAT
* : an asterisk is a wildcard variable that represents “all”
, : Commas break up scheduling values to form a list.
– : A hyphen represents a range of values in the schedule field.
/ : Forward slash with an asterisk to express a step value.

Some other examples are

Run the backup every minute.

* * * * * tar -zcf /var/backups/home.tgz /home/

Run the backup 12 minutes after every hour.

10 * * * * tar -zcf /var/backups/home.tgz /home/

Run the backup command every 15 minutes.

0,15,30,45 * * * * tar -zcf /var/backups/home.tgz /home/

Some shortcuts:

0 * * * * : Run hourly
0 0 * * * : Run daily
0 0 * * 0 : Run weekly
0 0 1 * * : Run monthly
0 0 1 1 * : Run yearly

0 0 1 1 * tar -zcf /var/backups/home.tgz /home/

The above command run yearly.

List all scheduled cron jobs:

You can check all all scheduled cron jobs in your Ubuntu system using below command.

crontab -l

Delete the user’s crontab:

You can erase your crontab with the below command.

crontab -r -i

 

If you liked this article, please subscribe to our YouTube Channel. You can also stay connected with us on X (Twitter) and Facebook.



Leave a Reply