crontab

Setting up a crontab (Cron Job) on Linux/macOS is simple. Here's how you can do it:


Step 1: Open the Crontab Editor

Run the following command in your terminal:

crontab -e

If it's your first time, it may ask you to choose an editor. Select one (like nano or vim).


Step 2: Understand the Crontab Syntax

A cron job follows this format:

* * * * * command_to_run
| | | | |
| | | | └── 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)

For example:

0 12 * * * /path/to/script.sh

This runs the script every day at 12:00 PM.


Step 3: Add a Cron Job

Let's say you want to run a Python script every day at 3 AM:

  1. Open crontab with crontab -e.

  2. Add the following line:

    (Make sure the Python path and script path are correct.)


Step 4: Save and Exit

  • In nano, press CTRL + X, then Y, and hit Enter.

  • In vim, press ESC, type :wq, and hit Enter.


Step 5: Verify Your Crontab

To check existing cron jobs, use:


Step 6: Check Cron Logs (Optional)

If the job isn't running, check logs:


Example Crontab Entries

Schedule
Cron Expression
Meaning

Every minute

* * * * *

Runs every minute

Every hour

0 * * * *

Runs at the start of every hour

Every day at 3 AM

0 3 * * *

Runs daily at 3:00 AM

Every Sunday at 4 PM

0 16 * * 0

Runs every Sunday at 4 PM

Every 10 minutes

*/10 * * * *

Runs every 10 minutes


Let me know if you need help setting up a specific cron job! πŸš€

Last updated