Skip to content

ZPMLabs/php-cron-manager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP Cron Manager

A clean and easy-to-use PHP package for managing cron jobs on Unix-like systems (Linux, macOS, etc.). This package allows you to programmatically add, update, remove, and list cron jobs with support for both standard cron expressions and human-readable schedules.

Features

  • ✅ List all cron jobs with standard cron times and human-readable descriptions
  • ✅ Add new cron jobs using standard cron format or human-readable expressions
  • ✅ Update existing cron jobs
  • ✅ Remove cron jobs
  • ✅ Windows detection with appropriate exception handling
  • ✅ Clean, object-oriented API
  • ✅ Comprehensive test coverage

Requirements

  • PHP 8.0 or higher
  • Unix-like operating system (Linux, macOS, etc.)
  • crontab command available in PATH
  • Windows is not supported (throws UnsupportedOSException)

Installation

composer require zpmlabs/php-cron-manager

Usage

Basic Example

<?php

require 'vendor/autoload.php';

use ZPMLabs\CronManager\CronManager;
use ZPMLabs\CronManager\CronJob;

// Create a new CronManager instance
$manager = new CronManager();

// List all cron jobs
$crons = $manager->listCrons();
foreach ($crons as $cron) {
    echo "Schedule: " . $cron->getSchedule() . "\n";
    echo "Command: " . $cron->getCommand() . "\n";
    echo "Comment: " . ($cron->getComment() ?? 'N/A') . "\n";
    echo "---\n";
}

List Cron Jobs with Human-Readable Schedules

$crons = $manager->listCronsWithHumanReadable();

foreach ($crons as $cron) {
    echo "Schedule: " . $cron['schedule'] . "\n";
    echo "Human-readable: " . $cron['human_readable'] . "\n";
    echo "Command: " . $cron['job']->getCommand() . "\n";
    echo "---\n";
}

Add Cron Jobs

Using Human-Readable Expressions

// Add a cron job that runs every minute
$manager->addCron('every minute', '/usr/bin/php /path/to/script.php', 'Runs every minute');

// Add a cron job that runs every hour
$manager->addCron('every hour', '/usr/bin/php /path/to/script.php', 'Hourly task');

// Add a cron job that runs every day at midnight
$manager->addCron('every day', '/usr/bin/backup.sh', 'Daily backup');

// Add a cron job with custom interval
$manager->addCron('every 5 minutes', '/usr/bin/php /path/to/script.php');
$manager->addCron('every 2 hours', '/usr/bin/php /path/to/script.php');
$manager->addCron('every 3 days', '/usr/bin/php /path/to/script.php');

Using Standard Cron Format

// Standard cron format: minute hour day month weekday
$manager->addCron('0 0 * * *', '/usr/bin/php /path/to/script.php', 'Daily at midnight');
$manager->addCron('*/15 * * * *', '/usr/bin/php /path/to/script.php', 'Every 15 minutes');
$manager->addCron('0 9 * * 1', '/usr/bin/php /path/to/script.php', 'Every Monday at 9 AM');

Using CronJob Object

$cronJob = new CronJob(
    '0 0 * * *',
    '/usr/bin/php /path/to/script.php',
    'Daily backup'
);

$manager->addCron($cronJob);

Update Cron Jobs

// Get all cron jobs
$crons = $manager->listCrons();

// Update the first cron job (index 0)
$manager->updateCron(0, 'every hour', '/usr/bin/php /path/to/new_script.php', 'Updated job');

// Or update using CronJob object
$updatedJob = new CronJob('0 */2 * * *', '/usr/bin/php /path/to/script.php', 'Every 2 hours');
$manager->updateCron(0, $updatedJob);

Remove Cron Jobs

// Remove a specific cron job by index
$crons = $manager->listCrons();
$manager->removeCron(0); // Remove the first cron job

// Remove all cron jobs
$manager->removeAllCrons();

Handle Windows (Unsupported OS)

try {
    $manager = new CronManager();
    // ... use the manager
} catch (\ZPMLabs\CronManager\Exception\UnsupportedOSException $e) {
    echo "Error: " . $e->getMessage() . "\n";
    // Handle Windows case - perhaps use Task Scheduler API instead
}

Supported Human-Readable Expressions

The following human-readable expressions are supported:

  • every minute* * * * *
  • every hour0 * * * *
  • every day0 0 * * *
  • every week0 0 * * 0
  • every month0 0 1 * *
  • every year0 0 1 1 *
  • every N minutes*/N * * * * (where N is 1-59)
  • every N hours0 */N * * * (where N is 1-23)
  • every N days0 0 */N * * (where N is 1-31)

You can also use standard cron expressions directly, which will be validated and used as-is.

API Reference

CronManager

Methods

  • __construct(?string $crontabPath = null) - Create a new CronManager instance
  • listCrons(bool $includeHumanReadable = false): array - List all cron jobs
  • listCronsWithHumanReadable(): array - List all cron jobs with human-readable schedules
  • addCron($scheduleOrJob, ?string $command = null, ?string $comment = null): bool - Add a new cron job
  • updateCron(int $index, $scheduleOrJob, ?string $command = null, ?string $comment = null): bool - Update an existing cron job
  • removeCron(int $index): bool - Remove a cron job by index
  • removeAllCrons(): bool - Remove all cron jobs

CronJob

Methods

  • __construct(string $schedule, string $command, ?string $comment = null) - Create a new CronJob
  • getSchedule(): string - Get the cron schedule
  • getCommand(): string - Get the command to execute
  • getComment(): ?string - Get the optional comment
  • setSchedule(string $schedule): void - Set the cron schedule
  • setCommand(string $command): void - Set the command
  • setComment(?string $comment): void - Set the comment
  • toCrontabLine(): string - Convert to crontab line format
  • static fromCrontabLine(string $line): self - Create from crontab line

CronExpressionParser

Static Methods

  • static parse(string $expression): string - Parse human-readable expression to cron format
  • static isValidCronExpression(string $expression): bool - Validate cron expression
  • static toHumanReadable(string $cronExpression): string - Convert cron expression to human-readable

Testing

Run the test suite:

composer test

Or using PHPUnit directly:

vendor/bin/phpunit

Important Notes

  1. Windows Support: This package does not support Windows. Windows uses Task Scheduler instead of cron. Attempting to use this package on Windows will throw an UnsupportedOSException.

  2. Permissions: The script must have permission to modify the user's crontab. Typically, this means running as the user whose crontab you want to modify.

  3. Backup: Always backup your crontab before making programmatic changes. You can do this manually with:

    crontab -l > crontab_backup.txt
  4. Index-based Operations: When updating or removing cron jobs, use the index from listCrons(). The index is 0-based and corresponds to the order in which cron jobs appear in the crontab.

License

MIT

Author

ZPMLabs

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages