Installation:
composer require cron/cron-bundle
Add to config/bundles.php (Symfony 5+):
return [
// ...
Cron\CronBundle\CronCronBundle::class => ['all' => true],
];
Database Setup:
php bin/console make:migration
php bin/console doctrine:migrations:migrate
First Use Case: Define a job via annotation or YAML:
// src/Command/MyCronJob.php
use Cron\CronBundle\Annotation\Cron;
class MyCronJob {
/**
* @Cron("0 0 * * *")
*/
public function run() {
// Your logic here
}
}
Register the job in config/packages/cron.yaml:
cron:
jobs:
my_job:
class: App\Command\MyCronJob
method: run
schedule: "0 0 * * *"
Test Locally:
php bin/console cron:list # Verify jobs
php bin/console cron:run # Execute manually
Job Definition:
@Cron("schedule") (e.g., @Cron("*/5 * * * *") for every 5 minutes).config/packages/cron.yaml for maintainability:
cron:
jobs:
cleanup:
class: App\Command\CleanupCommand
method: execute
schedule: "0 0 3 * *" # Daily at 3 AM
timezone: "Europe/Berlin"
Execution:
php bin/console cron:run [job_name] (e.g., php bin/console cron:run cleanup).* * * * * cd /path/to/project && php bin/console cron:run >> /dev/null 2>&1
Or use Systemd Timer (Symfony 5+):
# /etc/systemd/system/cron-jobs.timer
[Unit]
Description=Run Symfony cron jobs
[Timer]
OnCalendar=*-*-* *:0/5 # Every 5 minutes
Persistent=true
[Install]
WantedBy=timers.target
Logging & Monitoring:
config/packages/cron.yaml:
cron:
logging: true
php bin/console cron:log or Symfony’s default logger.Dependency Injection:
class MyJob {
public function __construct(private MailerInterface $mailer) {}
#[Cron("0 0 12 * *")]
public function sendDailyReport() {
$this->mailer->send(...);
}
}
Environment-Specific Schedules:
%env% in schedules (Symfony 5+):
cron:
jobs:
deploy_check:
schedule: "%env(DEPLOY_CHECK_CRON)%" # e.g., "*/10 * * * *"
Laravel-Specific Adaptations:
AppKernel with config/bundles.php (Symfony 5+).Artisan facade to trigger jobs:
Artisan::call('cron:run', ['job' => 'my_job']);
laravel-scheduler package for hybrid setups.Queue Integration:
#[Cron("0 * * * *")]
public function asyncTask() {
dispatch(new ProcessAsyncTask());
}
Testing:
CronManager in PHPUnit:
$this->cronManager = $this->createMock(CronManager::class);
$this->cronManager->expects($this->once())
->method('runJob')
->with('my_job');
Timezone Mismatches:
cron:
timezone: "America/New_York"
php bin/console cron:list --verbose to confirm timezone.Database Locking:
cron_job table to track runs. Ensure your DB supports transactions to avoid race conditions during migrations.Crontab Permissions:
bin/console:
chmod +x bin/console
sudo -u www-data php bin/console cron:run
Job Overlaps:
Messenger component or Laravel Queues.Annotation vs. YAML:
services.yaml includes:
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/'
excludes: ['../src/{Kernel.php,Tests}']
Logs:
config/packages/cron.yaml:
cron:
debug: true
var/log/dev.log for execution details.Dry Runs:
php bin/console cron:list --next-run
Common Errors:
cron.yaml and the class/method exists.date in your terminal to confirm the server’s timezone:
date +"%Z %z"
Custom Job Storage:
CronJobRepository to use a custom storage backend (e.g., Redis):
// src/Cron/CustomJobRepository.php
class CustomJobRepository extends DoctrineJobRepository {
public function __construct(Connection $connection, string $table = 'custom_cron_jobs') {
parent::__construct($connection, $table);
}
}
Register in config/services.yaml:
services:
Cron\CronBundle\Repository\CronJobRepository:
class: App\Cron\CustomJobRepository
Pre/Post Hooks:
CronJob entity to add lifecycle callbacks:
#[ORM\Entity]
class CronJob extends BaseCronJob {
#[PrePersist]
public function setCreatedAt(): void {
$this->createdAt = new \DateTime();
}
}
Dynamic Schedules:
#[Cron("0 0 * * *")]
public function updateDynamicJobs() {
$schedules = $this->scheduleRepository->findAll();
foreach ($schedules as $schedule) {
$this->cronManager->addJob($schedule->getName(), $schedule->getClass(), [
'method' => $schedule->getMethod(),
'schedule' => $schedule->getCronExpression(),
]);
}
$this->cronManager->saveJobs();
}
Event Listeners:
CronJobRunEvent):
// src/EventListener/CronListener.php
class CronListener implements EventSubscriberInterface {
public static function getSubscribedEvents(): array {
return [
CronJobRunEvent::NAME => 'onJobRun',
];
}
public function onJobRun(CronJobRunEvent $event): void {
// Log or modify job execution
}
}
How can I help you explore Laravel packages today?