How to create a cron job on Linux

Endrit Qerreti

Endrit Qerreti

In this tutorial you will learn how to create a cron job on Linux. Cron jobs are tasks that will run automatically on the date given. For example, instead of leaving the terminal shell open or running a script as background process with cron you don't have to do this.

Step 1 - Choose script/app

Before you create the cron job, you need to have the directory of the script/app that you want to run.

Example: The script that I want cron to run is called myapp.sh and it is located on my desktop, so to run this script in cron you need to have directory of the app as shown on the example below

/home/owlhowto/Desktop/myapp.sh

Step 2 - Set time when to run the script

If you are unsure about how the time syntax works on cron, then you can use a cronjob expression generator. This tool will let you specify when you want the script executed and it will automatically convert your choice into an expression for cron.

Here's some Examples

Time Cronjob Config
Run your script every hour 0 * * * * /root/owlhowto/myapp.sh
Run your script every 6 hours 0 */6 * * * /root/owlhowto/myapp.sh
Run your script every 12 hours 0 */12 * * * /root/owlhowto/myapp.sh
Run your script every 24 hours 0 0 * * * /root/owlhowto/myapp.sh
Run your script on Saturday 0 0 * * SAT /root/owlhowto/myapp.sh
Run Your script on Sunday 0 0 * * SUN /root/owlhowto/myapp.sh
Run Your script on Monday 0 0 * * MON /root/owlhowto/myapp.sh
Run Your script on Tuesday 0 0 * * TUE /root/owlhowto/myapp.sh
Run your script on Wednesday 0 0 * * WED /root/owlhowto/myapp.sh
Run your script on Thursday 0 0 * * THU /root/owlhowto/myapp.sh
Run your script on Friday 0 0 * * FRI /root/owlhowto/myapp.sh

Step 3 - Create Cron Job

Now that you have the path of the script, run the command below to create a cron job

crontab -e

The command above will open crontab config file in editing mode and will let you add your cron task

The correct syntax of cron is

0 1 * * * /home/owlhowto/Desktop/myapp.sh

The config above is scheduled to run every day at 1:00 AM.  

You can change the time to your preference, then simply add this line to the crontab file, and cron config file should look like this

In this example I'm redirecting the output of the app to /dev/null, /dev/null 2>&1 means both standard error and standard output generated by myapp.sh will go to /dev/null. If you want to see the ouput of the app that you are running remove the /dev/null 2>&1 from the end of line of your cronjob, then your script will generate stderr and stdout.

The cronjob should look like this

0 1 * * * /home/owlhowto/Desktop/myapp.sh

Once you have configured crontab, press CTRL + X to save the changes you made

Conclusion

In this tutorial you learned how to create a cronjob task on Linux.