Post

Cron Job Commands

How Does a Cron Job Work?

  1. Cron Daemon (crond):
    • The cron daemon is a program that constantly runs in the background and checks every minute to see if there’s a scheduled task that needs to be executed.
  2. Crontab (Cron Table):
    • The crontab is a file where you list all the tasks you want to schedule. Think of it as a “to-do list” for your computer.
  3. Format of a Cron Job:
    • Each line in the crontab represents one task.
    • A line has two parts:
      1. Schedule (When the task should run).
      2. Command (What the task should do).

Basic Format of a Cron Job

A cron job has 5 fields to define the schedule, followed by the command to run:

1
MINUTE HOUR DAY MONTH WEEKDAY COMMAND
  • MINUTE: (0–59) What minute of the hour?
  • HOUR: (0–23) What hour of the day?
  • DAY: (1–31) What day of the month?
  • MONTH: (1–12) Which month?
  • WEEKDAY: (0–6) Which day of the week? (0 = Sunday, 1 = Monday, etc.)
  • COMMAND: The program or script to run.

Examples:

1. Reboot the system every day at 5:00 AM:

1
0 5 * * * /sbin/reboot
  • 0: Minute = 0 (on the hour).
  • 5: Hour = 5 AM.
  • *: Any day of the month.
  • *: Any month.
  • *: Any weekday.

2. Delete temporary files at midnight on the 1st of every month:

1
0 0 1 * * rm -rf /tmp/*
  • 0 0: At 12:00 AM (midnight).
  • 1: On the 1st of the month.
  • *: Any month.
  • *: Any weekday.

3. Run a backup script every Friday at 6 PM:

1
0 18 * * 5 /path/to/backup.sh
  • 0 18: At 6:00 PM.
  • *: Any day.
  • 5: Friday.

How to Set a Cron Job

  1. Open your crontab file for editing:
    1
    
    crontab -e
    
  2. Add your task in the correct format.
  3. Save and exit the editor.

Check Your Cron Jobs

  • To view your scheduled jobs: ```bash crontab -l
This post is licensed under CC BY 4.0 by the author.