tourze/symfony-cron-job-bundle

Symfony 定时任务

Installs: 27 125

Dependents: 34

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

pkg:composer/tourze/symfony-cron-job-bundle

0.1.7 2025-06-23 14:14 UTC

This package is auto-updated.

Last update: 2025-10-31 07:49:18 UTC


README

English | 中文

[Latest Version] (https://packagist.org/packages/tourze/symfony-cron-job-bundle) [PHP Version] (https://packagist.org/packages/tourze/symfony-cron-job-bundle) [License] (https://packagist.org/packages/tourze/symfony-cron-job-bundle) [Build Status] (https://github.com/tourze/php-monorepo/actions) [Coverage Status] (https://codecov.io/gh/tourze/php-monorepo) [Quality Score] (https://scrutinizer-ci.com/g/tourze/symfony-cron-job-bundle) [Total Downloads] (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

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 crontab
  • cron:start - Start the cron scheduler daemon process
  • cron: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 name
  • setCronExpression(string $expression): Set the cron expression
  • setLockTtl(?int $ttl): Set the lock timeout
  • setOptions(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 execution
  • tourze/lock-service-bundle - For task locking mechanism
  • tourze/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.