Creating a Custom Cron Job on Linux

Automating routine tasks is essential in any robust system administration or web development workflow. Cron jobs provide a powerful, time-based job scheduler in Unix-like operating systems, allowing you to run scripts or commands automatically at scheduled intervals.

 What Is a Cron Job?

A cron job is a scheduled task defined in the system’s crontab (cron table) that executes commands or scripts at specified times or intervals. Cron is widely used because it’s:

  • Lightweight

  • Highly customizable

  • Built into most Linux distributions

 Common Use Cases

  • Daily or weekly database backups

  • Running PHP/Python scripts

  • Log rotation and cleaning temp files

  • Sending scheduled emails

  • Updating data caches or syncing files

Step 1: Access the Crontab

To edit your user’s crontab (without root access):

crontab -e
To edit the root crontab (requires sudo):
sudo crontab -e

Step 2: Cron Syntax Breakdown

Each cron job uses the following format:

* * * * * command_to_execute
│ │ │ │ │
│ │ │ │ └──── Day of the week (0-7, Sunday = 0 or 7)
│ │ │ └────── Month (1–12)
│ │ └──────── Day of the month (1–31)
│ └────────── Hour (0–23)
└──────────── Minute (0–59)

 Example: Run a script every day at 2 AM

0 2 * * * /home/user/scripts/backup.sh

Step 3: Create a Custom Script

Let’s say you want to run a custom Python script. First, create the file:

nano /home/user/scripts/cleanup.py

Sample script:

#!/usr/bin/env python3
import os
import datetime
log_dir = "/var/log/myapp"
threshold = 7 # days
now = datetime.datetime.now()
for filename in os.listdir(log_dir):
filepath = os.path.join(log_dir, filename)
if os.path.isfile(filepath):
file_age = now - datetime.datetime.fromtimestamp(os.path.getmtime(filepath))
if file_age.days > threshold:
os.remove(filepath)

Make the script executable:

chmod +x /home/user/scripts/cleanup.py

 Step 4: Add the Cron Job

Edit your crontab and add:

0 1 * * * /home/user/scripts/cleanup.py >> /var/log/cleanup.log 2>&1

This:

  • Runs the script daily at 1:00 AM

  • Logs output to /var/log/cleanup.log

 Example Use Cases

✅ Run every 10 minutes

*/10 * * * * /home/user/check_status.sh

✅ Run only on Mondays at 3 AM

0 3 * * 1 /home/user/scripts/weekly_report.sh

 Disable or Remove a Cron Job

Temporarily disable a line by commenting it out with #.

To remove all jobs:

crontab -r

Custom cron jobs are a powerful tool for automation, maintenance, and reliability. Whether you’re managing a personal VPS, deploying backend scripts, or running production workloads, mastering cron allows you to control when and how tasks run — effortlessly.