Photo by Andrea Piacquadio from Pexels

How to Schedule Tasks in Ubuntu using Cron

--

Recently I needed to schedule a task to run everyday on a specific time in one of my servers. So, I did some research on how to do it. I thought it would be great to share with others as well. So in this article I will covers how to schedule tasks to run automatically in a Linux environment using corn jobs. I will be using Ubuntu 18.04 server here. But this will work for any Linux environment you use.

What is cron? Cron is a job scheduling daemon found in Unix-like environments. We can use it to schedule tasks to run automatically on a scheduled date and time or scheduled intervals. Here a scheduled task will be called as a cron job. There is a specific way that we can schedule the tasks in the cron job. I will describe them in the later part of this tutorial.

First we have to install cron in our system. You can follow the below commands to install cron daemon.

~$ sudo apt update

~$ sudo apt install cron

~$ sudo systemctl enable cron

If you have run the above commands successfully then you have installed cron daemon in your machine.

Before getting it to the next job scheduling lets understand how to parameterized our job which helps us to specify the date and time we needed schedule our task. There are five fields that we can describe our scheduling time.

Below is the format of a cron job

minute hour day_of_the_month month day_of_the_week command_to_run

Before scheduling there is a small thing you should know. That is the cron daemon will refer you RTC time. You can check your RTC time by running the below command

~$ timedatectl

To setup our cronjob we have to edit our crontab file. To do it do the following,

~$ crontab -e

At the first time you will be asked to select a preferred editor. You can select a editor you like by inserting the number of the editor you like to use. I am using vim editor. So I choose 2. Then the crontab file will be opened for you.

There are lot of ways that you can schedule the job time. For our easiness we can use the below site to configure the time. If you are experienced you can simply learn the timing ways by a simple google search.

https://crontab.guru/

Here is a basic schedule that I have written

30 14 * * * ./script.sh

The about job will run a bash script that is named as script.sh at 2.30 pm at everyday. You can use the about crontab guru web app to schedule your time easily.

Then you can save and exit according to your selected editor commands.

That’s it. Now you have successfully scheduled a cron job 🙂

--

--