Cron Module Documentation
Prerequisites
Remember that you must have cron running and you must have added the line * * * * * php /home/fhmilkad/milk-admin/milkadmin/cron.php >/dev/null 2>&1
to your crontab file.
If you haven't done so, follow the tutorial on getting started.
Introduction
The Cron module provides a way to schedule recurring tasks in your application. It supports standard cron expressions, predefined intervals, and offers a fluent API for configuring job schedules.
Registering Cron Jobs
To register cron jobs in your application, you'll use the JobsContract service, which is accessible through the Get::make() method.
Basic Usage
Here's how to register a basic cron job:
// Get the jobs contract service
$jobs_contract = Get::make('jobs_contract');
// Register a job that runs at 1:30 AM every day
$jobs_contract::register(
'my_daily_report', // Unique name for the job
function() { // Callback function to execute
process_daily_reports();
return true; // Return true on success
},
'30 1 * * *', // Cron schedule expression
'Daily reporting process', // Description (optional)
true // Active status (optional)
);
Output
L'output del cron job (i print, echo, ecc) viene salvato nella tabella jobs_executions dentro output.
Se il job fallisce, viene salvato anche l'errore, se il jobs ritorna false viene registrato come failed.
Register Method Parameters
The register method accepts the following parameters:
- $name (string): A unique name to identify the job
- $callback (callable): The function or method to execute
- $schedule (string|CronDateManager): When to run the job (cron expression, predefined interval, or CronDateManager instance)
- $description (string, optional): Description of what the job does
- $active (bool, optional): Whether the job is active (default: true)
- $metadata (array, optional): Additional data to associate with the job
Using Predefined Intervals
You can use predefined intervals instead of cron expressions:
$jobs_contract = Get::make('jobs_contract');
// Register a job that runs hourly
$jobs_contract::register(
'cleanup_temp_files',
function() {
cleanup_temporary_files();
return true;
},
'hourly', // Predefined interval
'Temporary file cleanup'
);
// Available predefined intervals include:
// 'yearly', 'annually', 'monthly', 'weekly', 'daily', 'midnight',
// 'hourly', 'every_minute', 'every_5_minutes', 'every_10_minutes',
// 'every_15_minutes', 'every_30_minutes', 'twice_daily',
// 'weekdays', 'weekends'
Using the Fluent API
For more complex schedules, you can use the fluent API:
$jobs_contract = Get::make('jobs_contract');
// Create a scheduler for complex scheduling
$scheduler = $jobs_contract::createScheduler()
->setMinutes(0)
->setHours(9)
->setDayOfWeek('1-5'); // Monday to Friday
// Register the job with the scheduler
$jobs_contract::register(
'workday_morning_task',
function() {
send_morning_notifications();
return true;
},
$scheduler,
'Morning notification sender'
);
Initialization Hooks and Environments
The system provides different initialization hooks depending on the execution environment:
- init - Called when running in web environment (normal browser access)
- cli_init - Called when running in command-line interface (CLI)
- jobs_init - Called when running in cron job environment
Each module's module class (extending AbstractModule) can implement these corresponding methods:
class MyModuleModule extends \App\AbstractModule {
// Called in web environment
public function hookInit() {
// Web-specific initialization
}
// Called in CLI environment
public function cliInit() {
// CLI-specific initialization
}
// Called in cron environment
public function jobsInit() {
// Cron-specific initialization
}
}
When registering cron jobs, make sure to use the appropriate hook based on your environment. For cron jobs, use the jobs-init hook:
Implementing Custom Cron Jobs
The recommended place to add your custom cron jobs is in the milkadmin_local/functions.php file:
<?php
!defined('MILK_DIR') && die(); // Avoid direct access
// Register cron jobs
add_action('jobs-init', function() {
// Get the jobs contract service
$jobs_contract = Get::make('jobs_contract');
// Register a job that runs daily at midnight
$jobs_contract::register(
'my_custom_daily_job',
function() {
// Your job logic here
return true;
},
'daily',
'Daily maintenance job'
);
// Register a job with a custom cron expression
$jobs_contract::register(
'my_custom_weekly_job',
function() {
// Your job logic here
return true;
},
'0 3 * * 1', // Every Monday at 3:00 AM
'Weekly processing job'
);
});
Cron Expression Format
The Cron module supports the standard cron expression format:
* * * * *
│ │ │ │ │
│ │ │ │ └─── Day of week (0-6 or SUN-SAT)
│ │ │ └───── Month (1-12 or JAN-DEC)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)
Predefined Intervals
Instead of cron expressions, you can use these predefined intervals:
'yearly' => '0 0 1 1 *' // At 00:00 on January 1st
'annually' => '0 0 1 1 *' // Same as yearly
'monthly' => '0 0 1 * *' // At 00:00 on day 1 of every month
'weekly' => '0 0 * * 0' // At 00:00 on Sunday
'daily' => '0 0 * * *' // At 00:00 every day
'midnight' => '0 0 * * *' // Same as daily
'hourly' => '0 * * * *' // At minute 0 of every hour
'every_minute' => '* * * * *' // Every minute
'every_5_minutes' => '*/5 * * * *' // Every 5 minutes
'every_10_minutes'=> '*/10 * * * *' // Every 10 minutes
'every_15_minutes'=> '*/15 * * * *' // Every 15 minutes
'every_30_minutes'=> '*/30 * * * *' // Every 30 minutes
'twice_daily' => '0 0,12 * * *' // At 00:00 and 12:00
'weekdays' => '0 0 * * 1-5' // At 00:00 on weekdays
'weekends' => '0 0 * * 0,6' // At 00:00 on weekends
Advanced Scheduling with the Fluent API
For complex scheduling requirements, use the fluent API:
$jobs_contract = Get::make('jobs_contract');
// Create a scheduler for complex timing
$scheduler = $jobs_contract::createScheduler()
->setMinutes(30)
->setHours(14)
->setDayOfMonth(15)
->setMonth('1,4,7,10'); // January, April, July, October
// Register a job with the complex schedule
$jobs_contract::register(
'quarterly_report',
function() {
generate_quarterly_report();
return true;
},
$scheduler,
'Quarterly report generator that runs at 2:30 PM on the 15th of each quarter'
);
Special Characters in Cron Expressions
Cron expressions support several special characters:
- * - matches any value (e.g., * in the hour field means "every hour")
- , - value list separator (e.g., 1,3,5 means 1, 3, and 5)
- - - range of values (e.g., 1-5 means 1, 2, 3, 4, and 5)
- / - step values (e.g., */5 in minutes means every 5 minutes)
Job Execution Status and Return Function
Each job function receives a $metadata array parameter containing job-specific data and should return a boolean value. Here's how to implement your job function:
function myJobFunction($metadata) {
try {
// Your job logic here
echo "Processing task..."; // This will be saved to the output column
if (/* task successful */) {
return true; // Indicates successful execution
} else {
return false; // Indicates failed execution
}
} catch (\Exception $e) {
// The exception message will be saved to the errors column
throw new \Exception("Job failed: " . $e->getMessage());
}
}
Function Implementation Details
- Parameters - The function receives a
$metadataarray containing job-specific data - Return Value - Must return
truefor success orfalsefor failure - Exceptions - Throwing an exception will mark the job as failed and save the message to the errors column
- Output - Any content echoed or printed will be captured and saved to the output column
The cron system tracks the following information for each job:
- Last run time - When the job was last executed
- Next run time - When the job is scheduled to run next
- Success/failure - Whether the last execution was successful
- Error messages - Details of any failures
- Output - Text output from the job execution
Automatic Job Disabling
For reliability and system protection, a cron job will be automatically disabled if it fails 3 consecutive times. This prevents problematic jobs from continuously consuming system resources. You'll need to manually re-enable the job after investigating and fixing the cause of the failures.
Best Practices
- Keep jobs short and focused - Long-running jobs should be broken down or use a queuing system
- Handle failures gracefully - Implement proper error handling and logging
- Consider job frequency - Don't schedule jobs to run too frequently unless necessary
- Use descriptive job names - Names should indicate what the job does
- Return true/false - Always return a boolean result from your job functions
Conclusion
The Cron module provides a flexible way to schedule recurring tasks in your application. Add your custom cron jobs in the milkadmin_local/functions.php file using the Get::make('jobs_contract') service, or create custom modules for more complex scheduling needs.