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 article, we will use Cron to schedule a job to run every hour on Ubuntu 20.04 LTS (Focal Fossa).
- Ubuntu 20.04 LTS
- Sudo access
Note: The commands discussed in this article have been tested on Ubuntu 20.04 LTS (Focal Fossa).
Script to be scheduled
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/usman/
Enlist already scheduled 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.
Add a new cron job
The parameter –e is used to add a new job to cron.
$ crontab -e
The following file will open in our selected text editor.
Scroll down to the bottom of the file using the keyboard.
Here we will add our command.
0 */1 * * * /bin/sh /home/usman/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.
The following image represents the rest of the entities of the above command.
Let us write it in our file.
Save and close the file.
Observe the results
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, it can be observed that the utility runs as the hour begins and writes time with a date at the end of the file.
In this article, we share with you how a cron job can be scheduled to run every hour, and observe their results. Again, for any feedback use the comment section.
Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications including CCNA RS, SCP, and ACE. As an IT engineer and technical author, he writes for various websites.