Home | About | Categories | All Tips & Tutorials

Create a simple cronjob in Linux

ID: 199

Category: Linux Terminal

Added: 20th of October 2020

Updated On: Tutorial updated and rechecked on 1st of April 2023

Views: 2,595

In Linux you can automate tasks by creating a cronjobs. This can be especially helpful if for example you wanted to created a backup of your database everyday, calling a bash or .php script.

Getting your head around Cronjobs can be confusing at the start, so I will attempt to explain how they work with some really simple examples.

There are two parts to a cronjob. The first part is telling the system when you want to run the cron job, and the second part is telling the system what you want it to do using linux commands.

Part 1: Telling the system when to run your cronjob

This is set out using the following parameters
m=Minute
h=Hour
dom=Day of Month
mon=Month
dow=Day of Week

Run a cronjob at 10am on the 25th of December

m
h
dom
mon
dow

0
10
25
12
*


Run a cronjob at 10:10am on the 25th of December

m
h
dom
mon
dow

10
10
25
12
*


Run a cronjob at 10:10am on the 25 of Every Month

m
h
dom
mon
dow

10
10
25
*
*


Run a cronjob at 10:10am every day of the year

m
h
dom
mon
dow

10
10
*
*
*


Run a cronjob every minute, of every day, all year

m
h
dom
mon
dow

*
*
*
*
*



Part 2: Telling the system what to do
In this part you set your command. To keep things really simple we copy an image from the Pictures folder to the Desktop.
cp /home/username/Pictures/tux.png /home/username/Desktop


When we put it all together we get the following cron statement.
At 10:00am on the 25th December copy tux.png from the Pictures folder to Desktop
0 10 25 12 * cp /home/username/Pictures/tux.png /home/username/Desktop


How to set the cron job
To create a working cron job open your terminal and enter the following command.
crontab -e


Please note: You might want to set the time and date nearer to your own times and dates so you can see the cronjob in action.

You will notice the terminal will open with nano editor. Enter the information below the commented out section. Remember to replace username with your own username

0 10 25 12 * cp /home/username/Pictures/tux.png /home/username/Desktop






Once you have entered the information, do the following

1) Press CTRL + o to save, and then press enter to confirm

2) Press CTRL + x to exit nano

Your cronjob has now been saved.

To view the cronjob you just created, open your terminal and enter the following command
crontab -l




If you have set the times and date nearer to your own time and date, the cronjob should now be ready to go.

This is a just a very basic example and only covers a small part of cron, but is enough to give you a starting point.

If you visit https://crontab.guru/ you can try different cron schedule expressions