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

Expression
Meaning
When it runs

* * * * *

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

Server Health Monitoring

Monitor server health and send alerts when issues detected.

Expiration Reminder Notifications

Send reminders to users about expiring servers.

Automatic Backup Cleanup

Clean up old server backups to free storage space.

Analytics Data Aggregation

Aggregate and process analytics data for reporting.

Error Handling

Conditional Execution

Best Practices

  1. Keep tasks fast - they block other tasks

  2. Handle errors gracefully - don't let exceptions break cron

  3. Log execution - track when tasks run and their results

  4. Use appropriate schedules - don't run tasks more often than needed

  5. Make tasks idempotent - safe to run multiple times

  6. Check isEnabled() - allow users to disable tasks

  7. Monitor performance - track execution time and memory

  8. Batch operations - process data in chunks to avoid memory issues

Monitoring Cron Tasks

Check task execution:

Last updated