The Cron daemon is a built-in Linux utility that runs processes on your system at a scheduled time.
By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.
Basically, Cron is a utility that is used to schedule jobs according to a specific week, month, day, time, or time intervals. It is a time-based job scheduler that is pre-installed in Unix-like operating systems: Mac and Linux.
In this context, we shall look into how to use Cron to schedule a job to run every hour on Ubuntu 20.04 LTS (Focal Fossa).
Steps to Schedule a Job in Cron on Ubuntu ?
To do this, you need to log into the server as the root user with sudo rights.
1. Preparing the Script to be scheduled ?
Then, We need a small script that can be run as a job by Cron.
For this purpose, we have used the date command in our script. The output of a command is date and time which is routed to file.txt using >> directive.
date >> file.txt
Open a file (we name it demo.sh here). Write this snippet in the file, save, and exit. The file will be saved in our current directory which is /home/linuxapt/
2. How to Enlist already scheduled Cron jobs ?
The jobs that are already scheduled in the crontab can be enlisted using the following command:
$ crontab –l
Since we are enlisting the jobs here before initiating any, it reasonably prompts "no crontab for user".
Let us add our first cron job now.
3. How to Add a new cron job ?
The parameter –e is used to add a new job to cron:
$ crontab -e
This will open the Crontab text editor where you can input the cron values.
Here, Scroll down to the bottom of the file using the keyboard.
i. Now we will add our command:
0 */1 * * * /bin/sh /home/linuxapt/demo.sh
The first entity represents that the job should execute at the zeroth minute.
The second entity represents that it should run after an interval of an hour.
Shell in which script is coded and the script itself is mentioned in the next sections of the job.
ii. After writing it in the file, you can Save and close the file.
4. How to check the Cron output?
We will use cat utility to observe the results. The utility dumps the content of the file on the command line.
$ cat file.txt
Here, you will see that the utility runs as the hour begins and writes time with a date at the end of the file.