How to Schedule Tasks with Cron Jobs on Linux Print

  • cron, cronjob, schedule task, task, schedule, vps
  • 0

Cron jobs allow you to schedule repetitive tasks on your VPS, such as backups, script execution, updates, and maintenance. This guide explains how to set up and manage cron jobs in Linux.

 


 

What is a Cron Job?

 

A cron job is a scheduled task defined in the system’s crontab (cron table). It runs automatically at specified intervals.

 


 

Step 1: Open the Crontab File

 

To edit the crontab for the current user:

crontab -e

The first time you run this, it may ask you to select an editor (choose nano if you’re unsure).

 


 

Step 2: Understand the Cron Format

 

Each line in the crontab has the following 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)

 

 


 

Step 3: Example Cron Job Entries

Task

Cron Expression

Example

Run every minute

* * * * *

echo "Hello" >> /tmp/hello.log

Run daily at midnight

0 0 * * *

/usr/bin/php /var/www/html/cron.php

Run every Sunday at 2 AM

0 2 * * 0

/root/weekly-backup.sh

Run every 5 minutes

*/5 * * * *

curl -s http://localhost/healthcheck

 

 


 

Step 4: View Current Cron Jobs

 

To list current cron jobs for the current user:

crontab -l

 

 


 

Step 5: Remove Cron Jobs

 

To remove all cron jobs for the current user:

crontab -r

To remove individual jobs, use crontab -e and delete the specific lines manually.

 


 

Step 6: Schedule a Cron Job for Another User (as root)

 

Edit another user’s crontab:

crontab -u username -e

 

 


 

Step 7: Redirect Output (Optional)

 

By default, cron sends output by email (if configured). To prevent this or log to a file:

• Suppress output:

* * * * * /path/to/command > /dev/null 2>&1

 

• Log output to a file:

* * * * * /path/to/script.sh >> /var/log/myscript.log 2>&1

 

 


 

Step 8: Confirm Cron is Running

 

Ensure the cron service is active:

Debian/Ubuntu:

systemctl status cron

 

CentOS/AlmaLinux:

systemctl status crond

 

 

If inactive, start it with:

systemctl start cron        # Debian/Ubuntu
systemctl start crond       # CentOS/RHEL

 

 


 

Conclusion

 

Cron jobs are a powerful way to automate system tasks and maintenance on your VPS. Use them wisely to save time and streamline operations.

 

For help setting up or troubleshooting cron jobs, contact Hosteons Support or access your server via https://vps.hosteons.com.

 


Was this answer helpful?

« Back