tourze / symfony-cron-job-bundle
Symfony 定时任务
Installs: 28 398
Dependents: 37
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/tourze/symfony-cron-job-bundle
Requires
- ext-pcntl: *
- ext-posix: *
- composer/ca-bundle: ^1.5.6
- doctrine/collections: ^2.3
- doctrine/dbal: ^4.0
- doctrine/orm: ^3.0
- doctrine/persistence: ^4.1
- dragonmantank/cron-expression: ^3.4
- easycorp/easyadmin-bundle: ^4
- knplabs/knp-menu: ^3.7
- monolog/monolog: ^3.1
- psr/cache: ^2.0 || ^3.0
- psr/container: ^1.1|^2.0
- psr/log: ^3|^2|^1
- symfony/cache-contracts: ^3
- symfony/config: ^7.3
- symfony/console: ^7.3
- symfony/dependency-injection: ^7.3
- symfony/event-dispatcher: ^7.3
- symfony/framework-bundle: ^7.3
- symfony/http-foundation: ^7.3
- symfony/http-kernel: ^7.3
- symfony/lock: ^7.3
- symfony/messenger: ^7.3
- symfony/process: ^7.3
- symfony/property-access: ^7.3
- symfony/routing: ^7.3
- symfony/validator: ^7.3
- symfony/var-dumper: ^7.3
- symfony/yaml: ^7.3
- tiben/crontab-manager: ^1.4
- tourze/async-command-bundle: 1.0.*
- tourze/async-contracts: 1.0.*
- tourze/bundle-dependency: 1.*
- tourze/doctrine-helper: 1.0.*
- tourze/doctrine-timestamp-bundle: 1.0.*
- tourze/easy-admin-menu-bundle: 1.0.*
- tourze/lock-service-bundle: 1.0.*
- tourze/symfony-dependency-service-loader: 1.0.*
- tourze/symfony-routing-auto-loader-bundle: 1.0.*
- twig/twig: ^3.21
Requires (Dev)
README
[]
(https://packagist.org/packages/tourze/symfony-cron-job-bundle)
[
]
(https://packagist.org/packages/tourze/symfony-cron-job-bundle)
[
]
(https://packagist.org/packages/tourze/symfony-cron-job-bundle)
[
]
(https://github.com/tourze/php-monorepo/actions)
[
]
(https://codecov.io/gh/tourze/php-monorepo)
[
]
(https://scrutinizer-ci.com/g/tourze/symfony-cron-job-bundle)
[
]
(https://packagist.org/packages/tourze/symfony-cron-job-bundle)
A Symfony bundle for managing and running cron jobs with flexible scheduling, registration, and async execution support. Features anti-duplicate execution, HTTP triggers, and Twig integration for serverless environments.
Table of Contents
- Quick Start
- Features
- Advanced Usage
- Serverless Integration
- Environment Configuration
- Available Commands
- API Reference
- Interfaces
- Configuration
- Contributing
- License
- Changelog
Quick Start
Requirements
- PHP >= 8.1
- Symfony >= 6.4
- Extensions:
posix,pcntl
Installation
Install via Composer:
composer require tourze/symfony-cron-job-bundle
1. Register a Cron Job
Use the AsCronTask attribute on your Symfony command:
use Tourze\Symfony\CronJob\Attribute\AsCronTask; #[AsCronTask('0 * * * *')] // runs every hour class MyHourlyCommand extends Command { ... }
Or implement the CronCommandProvider interface to provide jobs dynamically.
2. Enable the Bundle
Add the bundle to your bundles.php file:
return [ // ... other bundles Tourze\Symfony\CronJob\CronJobBundle::class => ['all' => true], ];
3. Add Cron Entry
php bin/console cron-job:add-cron-tab
This registers the main cron entry in your system crontab.
4. Start the Scheduler
php bin/console cron:start
This starts a process to check and run due cron jobs every minute.
5. Manual Execution
php bin/console cron:run
Manually trigger and run all cron jobs that are due at the current time.
Features
- Multiple Registration Methods: Register cron jobs via PHP attribute or provider interface
- Auto-generate Crontab: Auto-generate crontab entries and manage them programmatically
- Asynchronous Execution: Execute scheduled commands asynchronously via Symfony Messenger
- Anti-duplicate Execution: Built-in locking mechanism prevents duplicate task execution
- HTTP Triggers: Support HTTP triggers for serverless environments (AWS Lambda, Function Compute, etc.)
- Twig Integration: Auto-trigger via JavaScript in templates
- Flexible Scheduling: Support for custom cron expressions with per-task lock TTL
- Symfony Integration: Integrates with Symfony Messenger, Lock, and Cache components
Advanced Usage
Custom Lock TTL
Configure custom lock timeout for specific tasks:
use Tourze\Symfony\CronJob\Attribute\AsCronTask; #[AsCronTask( expression: '*/5 * * * *', // Every 5 minutes lockTtl: 300 // Lock for 5 minutes (300 seconds) )] class MyCustomCommand extends Command { // ... command implementation }
Dynamic Job Registration
Implement the CronCommandProvider interface for dynamic job registration:
use Tourze\Symfony\CronJob\Provider\CronCommandProvider; use Tourze\Symfony\CronJob\Request\CommandRequest; class MyJobProvider implements CronCommandProvider { public function getCommands(): iterable { $request = new CommandRequest(); $request->setCommand('app:process-queue'); $request->setCronExpression('*/10 * * * *'); $request->setLockTtl(600); // 10 minutes $request->setOptions(['--env' => 'prod']); yield $request; } }
Serverless Integration
HTTP Triggers for Serverless
For serverless environments, use HTTP triggers:
# Direct HTTP request
curl -X POST https://your-app.com/cron/trigger
Twig Auto-trigger
Add auto-trigger functionality to your templates:
{# Basic usage: trigger every 60 seconds #}
{{ cron_auto_trigger() }}
{# Custom interval: trigger every 30 seconds #}
{{ cron_auto_trigger(30000) }}
{# With debug and retry options #}
{{ cron_auto_trigger(60000, {
debug: true,
maxRetries: 5,
retryDelay: 10000
}) }}
Environment Configuration
Configure auto-trigger interval via environment variables:
# .env CRON_AUTO_TRIGGER_INTERVAL=30000 # 30 seconds
Available Commands
cron-job:add-cron-tab- Add the main cron entry to system crontabcron:start- Start the cron scheduler daemon processcron:run- Run all cron jobs due at the current time
API Reference
AsCronTask Attribute
Configure cron jobs directly on command classes:
#[AsCronTask(
expression: '0 */6 * * *', // Every 6 hours
lockTtl: 21600 // Lock for 6 hours (21600 seconds)
)]
Parameters:
expression: Cron expression (default:'* * * * *')lockTtl: Lock timeout in seconds (default:null= 3600 seconds)
Interfaces
CronCommandProvider Interface
Implement this interface to provide dynamic cron jobs:
interface CronCommandProvider { public function getCommands(): iterable; }
CommandRequest Class
Configure dynamic cron job requests:
$request = new CommandRequest(); $request->setCommand('app:example'); $request->setCronExpression('0 2 * * *'); $request->setLockTtl(7200); $request->setOptions(['--batch-size' => 100]);
Methods:
setCommand(string $command): Set the command namesetCronExpression(string $expression): Set the cron expressionsetLockTtl(?int $ttl): Set the lock timeoutsetOptions(array $options): Set command options
CronTriggerService
Main service for triggering cron jobs:
public function triggerScheduledTasks(): bool
Returns true if tasks were triggered, false if already triggered this minute.
Configuration
Bundle Dependencies
This bundle depends on the following packages:
tourze/async-command-bundle- For asynchronous command executiontourze/lock-service-bundle- For task locking mechanismtourze/symfony-routing-auto-loader-bundle- For auto-routing
Cache Configuration
The bundle uses Symfony's cache system for anti-duplicate execution.
Configure your cache adapter in config/packages/cache.yaml:
framework: cache: app: cache.adapter.redis # Or your preferred adapter
Messenger Configuration
For asynchronous execution, configure Symfony Messenger:
# config/packages/messenger.yaml framework: messenger: transports: async: "%env(MESSENGER_TRANSPORT_DSN)%" routing: 'Tourze\AsyncCommandBundle\Message\RunCommandMessage': async
Contributing
- Open issues or pull requests on GitHub
- Follow PSR coding standards
- Write and run tests before submitting PRs
License
MIT License. See LICENSE for details.
Changelog
See Git history for latest changes and releases.