Cron Tasks
Schedule automated tasks to run periodically.
Cron Task Interface
<?php
namespace Plugins\MyPlugin\CronTask;
use App\Core\Cron\PluginCronTaskInterface;
use Psr\Log\LoggerInterface;
class MyCleanupTask implements PluginCronTaskInterface
{
public function __construct(
private readonly MyService $myService,
private readonly LoggerInterface $logger,
) {}
public function execute(): void
{
$this->logger->info('Running cleanup task');
try {
$deletedCount = $this->myService->cleanupOldData();
$this->logger->info('Cleanup completed', [
'deleted_count' => $deletedCount
]);
} catch (\Exception $e) {
$this->logger->error('Cleanup failed', [
'error' => $e->getMessage()
]);
throw $e;
}
}
public function getSchedule(): string
{
// Cron expression
return '0 3 * * *'; // Daily at 3 AM
}
public function getName(): string
{
return 'my-plugin:cleanup';
}
public function getDescription(): string
{
return 'Clean up old data from my-plugin tables';
}
public function isEnabled(): bool
{
// Control whether task should run
return true;
}
}Cron Expression Syntax
* * * * *
Every minute
Every minute
*/5 * * * *
Every 5 minutes
:00, :05, :10, ...
0 * * * *
Every hour
Top of every hour
0 */6 * * *
Every 6 hours
00:00, 06:00, 12:00, 18:00
0 3 * * *
Daily at 3 AM
Once per day
0 0 * * 0
Weekly on Sunday
Sunday at midnight
0 0 1 * *
Monthly on 1st
First day of month
Cron Expression Format
Advanced Cron Task
Service Registration
Important: Cron tasks must be tagged with plugin.cron_task.
Task Examples
Daily Database Cleanup
Hourly Data Sync
Weekly Report Generation
Error Handling
Conditional Execution
Best Practices
Keep tasks fast - they block other tasks
Handle errors gracefully - don't let exceptions break cron
Log execution - track when tasks run and their results
Use appropriate schedules - don't run tasks more often than needed
Make tasks idempotent - safe to run multiple times
Check isEnabled() - allow users to disable tasks
Monitor performance - track execution time and memory
Batch operations - process data in chunks to avoid memory issues
Monitoring Cron Tasks
Check task execution:
Related Guides
Console Commands - Manual task execution
Dependencies - Service injection
Best Practices - Performance optimization
Last updated