halloverden/symfony-scheduled-task-bundle

Enables the creation of cron-jobs tasks to be consumed by symfony/messenger

2.0.0 2022-09-08 11:31 UTC

This package is auto-updated.

Last update: 2024-11-08 16:16:29 UTC


README

The Scheduled Task Bundle provides a way to implement cron jobs in your Symfony application, making use of the messenger component to execute the jobs either synchronously or asynchronously.

Installation

Make sure Composer is installed globally, as explained in the installation chapter of the Composer documentation.

Applications that use Symfony Flex

Open a command console, enter your project directory and execute:

$ composer require halloverden/symfony-scheduled-task-bundle

Applications that don't use Symfony Flex

Step 1: Download the Bundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

$ composer require halloverden/symfony-scheduled-task-bundle

Step 2: Enable the Bundle

Then, enable the bundle by adding it to the list of registered bundles in the config/bundles.php file of your project:

// config/bundles.php

return [
    // ...
    HalloVerden\ScheduledTaskBundle\HalloVerdenScheduledTaskBundle::class => ['all' => true],
];

Usage

  • Route your messages to the transports by defining your own messenger logic in your config/packages/messenger.yaml file. For example, see Resources/config/hallo_verden_scheduler.yaml:
framework:
    messenger:
        routing:
            'HalloVerden\ScheduledTaskBundle\Interfaces\AsyncTaskInterface': async_task
            'HalloVerden\ScheduledTaskBundle\Interfaces\SyncTaskInterface': sync
  • Make sure all the transports you want to use are configured under transports: in your config/packages/messenger.yaml file. For example, see Resources/config/hallo_verden_scheduler.yaml:
framework:
    messenger:
        transports:
            async_task: '%env(MESSENGER_TRANSPORT_DSN)%'
            sync: 'sync://'

N.B. Enabling the failure_transport is recommended.

  • Create a Task class that implements the AsyncTaskInterface or the SyncTaskInterface and define the schedule and the name for the Task:
class RandomScheduledTask implements AsyncTaskInterface {

  public function getSchedule(): ScheduleInterface {
    return SimpleCronExpression::monthly()->day(23)->hour(16)->minute(25);
  }
  public function getName(): string {
    return 'random-scheduled-task';
  }
}
  • Create a TaskHandler class for your task which will need to define an __invoke(Taskclass $task) method:
class RandomScheduledTaskHandler implements TaskHandlerInterface {

  public function __invoke(RandomScheduledTask $task) {
    //...
  }
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT