Step by Step guide for Cron Jobs

Step by Step guide for Cron Jobs

ยท

3 min read

What is a Cron Job?

Cron is a time-based job scheduler in Unix-like operating systems. It allows users to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals.

Components of a Cron Job:

A cron job consists of:

  1. Schedule Expression: Defines when the job should run. It includes minute, hour, day of the month, month, and day of the week fields.

  2. Command or Script: The actual task or command that should be executed.

Basic Syntax of a Cron Job:

* * * * * command_to_be_executed
| | | | |
| | | | +----- Day of the Week (0 - 6) (Sunday to Saturday)
| | | +------- Month (1 - 12)
| | +--------- Day of the Month (1 - 31)
| +----------- Hour (0 - 23)
+------------- Minute (0 - 59)

Example: Scheduling a Cron Job

Let's schedule a simple cron job that echoes a message to a file every day at 2:30 PM.

Open your crontab file for editing:

  •     crontab -e
    

    Choose the nano editor & paste the below job

  • Add the following line to schedule the job:

  1.   30 14 * * * echo "Hello, this is a cron job!" >> /tmp/logfile.txt
    

    This expression means the job will run at 2:30 PM every day.

  2. Save and exit the editor. (for nano ctrl+x & press y)

Real-Time Example:

Let's consider a real-time example. Suppose you have a backup script that you want to run every day at midnight.

  1. Create a backup script, for example, backup.sh:
  •     #!/bin/bash
        tar -czvf /Users/prasad/Documents/backup_$(date +\%Y\%m\%d_\%H\%M\%S).tar.gz /tmp/backup_directory
    

    This script creates a compressed backup file with a timestamp.

  • Make the script executable:

  •     chmod +x backup.sh
    
  • Open your crontab file:

  •     vi crontab -e
    
  • Add the following line to schedule the backup script every day at midnight:

  1.   0 0 * * * /tmp/backup.sh
    

    This expression means the job will run at midnight (00:00) every day.

  2. Save and exit the editor.

Now, your backup script will automatically run every day at midnight.

Viewing Existing Cron Jobs:

To view your existing cron jobs, use the following command:

crontab -l

Important Tips:

  • Each user has their own crontab, so cron jobs are specific to individual users.

  • Be cautious while editing the crontab file, as an incorrect syntax can lead to issues.

  • Use absolute paths in your cron jobs to avoid any issues related to the working directory.

Image Credit:

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป https://nil.pro.np/set-up-cron-job-linux/

Did you find this article valuable?

Support Prasad Suman Mohan by becoming a sponsor. Any amount is appreciated!

ย