Scheduling PHP and Shell Script Tasks Using Cron Jobs

Scheduling PHP and Shell Script Tasks Using Cron Jobs

Learn how to schedule PHP and shell script tasks using cron jobs. Automate backups, log cleanup, email notifications, and server maintenance efficiently.

Introduction

Automating repetitive tasks such as backups, log cleanup, report generation, and email notifications is essential for maintaining server efficiency and reducing manual workload. Cron jobs allow scheduling PHP scripts and shell commands to run at specific intervals, making task automation seamless.

With cron jobs and PHP, you can:

  • Schedule database backups, log cleanup, and data processing
  • Automate recurring tasks without manual intervention
  • Optimize server performance by running tasks during off-peak hours
  • Generate reports and notifications automatically

This guide covers:

  • Setting up and managing cron jobs
  • Scheduling PHP scripts and shell commands
  • Logging cron execution and troubleshooting errors
  • Using PHP to manage cron jobs dynamically

1. Understanding Cron Jobs in Linux

A cron job is a scheduled task executed by the system at predefined intervals. The cron scheduler runs jobs based on the crontab (cron table) file.

To edit the cron jobs for the current user:

crontab -e

Cron Job Syntax

*    *    *    *    *   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)

Common Examples

Task Cron Syntax Execution Time
Run every minute * * * * * Every minute
Run every 5 minutes */5 * * * * Every 5 minutes
Run every hour 0 * * * * At the beginning of every hour
Run daily at midnight 0 0 * * * Every day at 12:00 AM
Run on the first day of the month 0 0 1 * * First day of every month

2. Scheduling a PHP Script with a Cron Job

To schedule a PHP script to run every hour, edit the crontab:

crontab -e

Add the following line:

0 * * * * php /var/www/html/task.php

Verifying the Cron Job

To list all scheduled cron jobs:

crontab -l

3. Running a Shell Script Using Cron Jobs

To schedule a Bash script execution every day at 3 AM:

0 3 * * * bash /var/www/scripts/backup.sh

Example: backup.sh (Database Backup Script)

#!/bin/bash
mysqldump -u root -p'password' database_name > /backups/db_backup_$(date +\%Y-\%m-\%d).sql
echo "Backup completed on $(date)" >> /var/log/backup.log

This script:

  • Creates a MySQL database backup
  • Appends a timestamp to the filename
  • Logs the execution time

4. Automating Log Cleanup Using Cron Jobs

To delete logs older than 7 days, add this cron job:

0 2 * * * find /var/log -type f -mtime +7 -delete

Why Use This?

  • Prevents log files from consuming excessive disk space
  • Ensures regular log rotation

5. Sending Automated Email Reports Using a PHP Cron Job

PHP Code (email_report.php)

$to = "admin@example.com";
$subject = "Daily Server Report";
$message = "This is an automated server report.";
$headers = "From: no-reply@example.com";

mail($to, $subject, $message, $headers);
echo "Email sent successfully.";

Cron Job to Send Reports Daily at 8 AM

0 8 * * * php /var/www/html/email_report.php

Why Use This?

  • Automates daily system monitoring reports
  • Provides regular updates without manual execution

6. Running a PHP Script in the Background Using Cron Jobs

For long-running scripts, use nohup to prevent execution from stopping:

0 0 * * * nohup php /var/www/html/long_task.php > /dev/null 2>&1 &

Why Use nohup?

  • Ensures cron job execution continues even if the session closes
  • Redirects output to prevent cluttering logs

7. Logging Cron Job Execution for Debugging

To log the output of a PHP script scheduled in a cron job:

0 * * * * php /var/www/html/task.php >> /var/log/task.log 2>&1

Checking Cron Logs

To verify cron job execution:

cat /var/log/syslog | grep CRON

Why Use Logging?

  • Helps debug failed cron jobs
  • Tracks successful executions

8. Managing Cron Jobs from a PHP Script

Adding a New Cron Job Using PHP

$cronJob = "0 3 * * * php /var/www/html/task.php >> /var/log/task.log 2>&1";
file_put_contents('/tmp/crontab.txt', shell_exec('crontab -l') . "\n" . $cronJob);
shell_exec('crontab /tmp/crontab.txt');
echo "Cron job added.";

Removing a Cron Job Using PHP

shell_exec('crontab -r');
echo "All cron jobs removed.";

Why Manage Cron Jobs in PHP?

  • Allows dynamic scheduling via web interface
  • Provides cron job automation in applications

9. Automating System Updates Using a Cron Job

To automatically update the system every Sunday at 2 AM:

0 2 * * 0 apt update && apt upgrade -y

Why Use This?

  • Ensures the server is always up to date
  • Reduces manual system maintenance efforts

10. Best Practices for Using Cron Jobs in PHP and Shell Scripts

  • Log cron job execution to track failures
  • Avoid running too many cron jobs at once
  • Use absolute paths for PHP and Bash scripts
  • Schedule tasks during off-peak hours to minimize server load
  • Secure cron jobs by restricting execution to trusted scripts

Conclusion

Scheduling PHP and shell script tasks using cron jobs ensures efficient automation, reducing manual workload and improving system reliability.

This guide covered:

  • Setting up cron jobs for PHP and shell scripts
  • Automating backups, log cleanup, and system monitoring
  • Logging cron executions for debugging
  • Managing cron jobs dynamically using PHP

By implementing these techniques, server maintenance and task execution become seamless and fully automated.

Leave a Reply