ScheduledTaskand its respective
ScheduledTaskHandlerare registered in a plugin's
services.xml. For it to be found by Shopware 6 automatically, you need to place the
services.xmlfile in a
Resources/config/directory, relative to the location of your plugin's base class. The path could look like this:
services.xmlcontaining a new
ScheduledTaskas well as a new
messenger.message_handler. Your custom task will now be saved into the database once your plugin is activated.
services.xmlfile tries to find both the task itself as well as the new task handler in a directory called
Service/ScheduledTask. This naming is up to you, Shopware 6 decided to use this name though.
ExampleTaskclass has to extend from the
Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskclass, which will force you to implement two methods:
getTaskName: The technical name of your task. Make sure to add a vendor prefix to your custom task, to prevent collisions with other plugin's scheduled tasks. In this example this is
getDefaultInterval: The interval in seconds at which your scheduled task should be executed.
ExampleTaskHandleras defined previously in your
services.xml, has to extend from the class
Shopware\Core\Framework\MessageQueue\ScheduledTask\ScheduledTaskHandler. This also comes with two methods, that you need to implement first:
getHandledMessages: An iterable, or an array, of the scheduled tasks, that this handler will take care of. In this case this is only the
run: This method is executed once your scheduled task is executed. Do everything, that your task is supposed to do here. In this example, it will just create a new file.
bin/console scheduled-task:run. This will start the
ScheduledTaskRunner, which takes care of your scheduled tasks and their respective timings. It will dispatch a message to the message bus once your scheduled task's interval is due.
bin/console messenger:consumeto actually execute the dispatched messages. Make sure, that the
statusof your scheduled task is set to
scheduled_tasktable, otherwise it won't be executed. This is not necessary, when you're using the admin worker.