Skip to Content
Module developmentModule basics

Commands and scheduled tasks

How a module adds its own php flute command and registers a background task that the owner sees in the admin scheduler.

By the end your module has its own php flute example:recount command and a scheduled task that cron runs every night, which the owner sees in the scheduler and can start by hand.

Minimal example

A command extends Command from Symfony Console. The core has no base class or attribute of its own: the name goes to parent::__construct(), dependencies come through the constructor.

app/Modules/Example/Console/RecountCommand.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Console;

use Flute\Modules\Example\Services\Payouts;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

final class RecountCommand extends Command
{
    public function __construct(
        private readonly Payouts $payouts,
    ) {
        parent::__construct('example:recount');
    }

    protected function configure(): void
    {
        $this->setDescription('Recounts payout totals for every player');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln(sprintf('Players recounted: %d', $this->payouts->recount()));

        return self::SUCCESS;
    }
}

The provider's boot() registers the command and the task:

app/Modules/Example/Providers/ExampleProvider.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\Example\Providers;

use DI\Container;
use Flute\Core\Scheduler\TaskScheduler;
use Flute\Core\Support\ModuleServiceProvider;
use Flute\Modules\Example\Console\RecountCommand;
use Flute\Modules\Example\Services\Cleanup;

final class ExampleProvider extends ModuleServiceProvider
{
    public function boot(Container $container): void
    {
        $this->bootstrapModule();

        if (is_cli()) {
            app()->getConsole()->addCommand($container->get(RecountCommand::class));
        }

        $container
            ->get(TaskScheduler::class)
            ->add('example.cleanup', [Cleanup::class, 'run'])
            ->daily('04:10')
            ->label('example.tasks.cleanup');
    }
}

The task's label in the admin panel comes from the module's translations:

app/Modules/Example/Resources/lang/en/example.php
<?php

return [
    'tasks' => [
        'cleanup' => 'Payouts: delete unconfirmed requests older than 30 days',
    ],
];

Check the result:

php flute list example
php flute example:recount
Players recounted: 128

The Reviews module adds its reviews:recount command this way, and the Tickets module schedules closing stale tickets every hour and cleaning up attachments at 04:10.

How it works

The php flute console loads the core and the modules the same way a web request does: register() and boot() of every module, then the core commands. bootRequest() never runs in the console, so a command registered there never shows up. The is_cli() check keeps a web request from building the command object and its dependencies.

Register tasks without is_cli(). The same boot() runs both in php flute cron:run, which runs the tasks, and on the admin scheduler page, which lists them. A task inside an is_cli() branch still runs, but the owner can neither see it nor start it by hand.

Pass the task callback as [SomeClass::class, 'method'] or as the name of a class with __invoke(). The container then builds the class only when the task runs. A ready object from $container->get() would be built on every request to the site.

The owner adds cron:run to crontab once a minute, as described in Scheduler. On each tick the tasks whose schedule slot has come up run. Each one runs under its own lock: if the previous run has not finished, the new one is skipped and cron:run prints skipped for the task. An exception in one task does not stop the others: the task gets the "Failed" status with the text in its row, and the details go to storage/logs/cron-<date>.log.

A missed slot (cron was down, a tick ran long) runs once, late. A task that has never run waits for its first slot: a daily task added in the afternoon first runs at 04:10 the next day.

From cron a task runs in a console process with no current user, request or session. "Run now" runs it inside an admin's request, but do not rely on that: whatever the task needs, it reads from the database and settings.

Reference

TaskScheduler methodWhat it does
add(string $name, callable|string|array $callback): ScheduledTaskregisters a task; a second task with the same name replaces the first, so start the name with the module key
all(): arrayevery task, keyed by name
get(string $name): ?ScheduledTaskone task or null
ScheduledTask methodSchedule
everyMinute()every minute, the default
everyMinutes(int $minutes)every N minutes: */N * * * *
hourly()at the start of every hour
daily(string $time = '00:00')once a day, time as HH:MM in the site's time zone
cron(string $expression)any five-field expression
label(string $label)the label in the admin panel: a translation key or text; without it the task name is shown

Core commands, cron:run among them, are listed in the CLI reference.

Common mistakes

The task is in the scheduler but never runs

Cron is not set up on the site: the scheduler shows a warning that background tasks are not running. To test a task without cron, use "Run now" in AdminScheduler, or wait for its slot after setting cron up as described on this page.

What you seeCause
Command "example:recount" is not defined.the command is registered in bootRequest(), or the module is disabled
the module's command does something elseits name matches a core command: core commands are added after the modules and replace commands with the same name. Start the name with the module key
the task runs but is missing from the schedulerit is registered inside an is_cli() branch or in bootRequest()
Invalid cron expression for task 'example.cleanup': ... while the module loadsa wrong expression in cron(), or a time such as daily('25:00')
Scheduled task 'example.cleanup' failed: Scheduled task callback is not callable. in cron.loga typo in the callback's method name, or the method is not public
the module has two tasks but the scheduler shows oneboth were added with the same name, the second replaced the first
the "Failed" status with "The run did not finish: the process died (fatal error, memory or time limit)."the process died in the middle of the task; from then on the task runs after the others. Split the work into batches

Learn more

On this page