Ubuntu

How to Schedule a Job in Cron to Run Every Hour in Ubuntu 20.04

Schedule a Job in Cron in Ubuntu 20.04

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).

Prerequisites

  • 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/

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.47528\img\cron1.png

Enlist already scheduled jobs

The jobs that are already scheduled in the crontab can be enlisted using the following command:

$ crontab –l

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.21467\img\cronList.png

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.

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.4742\img\cron3.png

Scroll down to the bottom of the file using the keyboard.

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.10567\img\cron4.png

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.

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.33813\cron.png

Let us write it in our file.

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.38023\img\cron9.png

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

C:\Users\MUHAMM~1\AppData\Local\Temp\Rar$DRa11832.35892\img\cron10.png

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.

 

Conclusion

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.

Similar Posts