Skip to main content
Go to homepage
Github

Task scheduling

Learn how to create scheduled tasks that can be run crontab-like, repeatedly or just once.

Setting up CRON

Before you begin, you need to configure the scheduling software available on your operating system to run the tasks.

In an environment that supports CRON, the following should be added:

* * * * * /usr/bin/php /path/to/my-app/run schedule:run >> /dev/null 2>&1

Setting up Windows

In Windows, the system that can be used is Task Scheduler , via a graphical interface (which may be more intuitive) or via a command, similar to this:

schtasks /create /tn "My Tasks" /tr "C:\php\php.exe C:\path\to\my-app\run.php schedule:run" /sc minute /mo 1 /f

Creating tasks

To test, add the following code to system/console.php:

use Inphinit\Experimental\Scheduling\Task; $mytask = $scheduler->action('hello', function (Task $task) { echo 'Hello world!'; }); // Define para tarefa a ser executada a cada hora $mytask->interval(3600);

Testing task

To test a task, regardless of scheduling, simply run the command:

./run schedule:run --task hello

Setting up the schedule

When adding a task, it is necessary to configure the trigger time and whether execution should occur in the background using the following methods:

Command Description
cron($minute, $hour, $day, $month, $weekday) Schedule the task using crontab-like fields.
interval(int $seconds) Schedule the task to run repeatedly at each specified interval of seconds, counting from its last execution.
once(string|DateTime $datetime) Schedule the task to run exactly once, on the specified date/time (or after). Once executed, it will not be performed again.
at(string $time) Shortcut to schedule a task for daily execution at a fixed time. Equivalent to cron($minute, $hour, '*', '*', '*').
runInBackground(bool $enable) This marks the task to be dispatched as an independent background process, rather than being executed synchronously within the scheduler process.

To experiment, you can use functions, closures, or a controller within the namespace Tasksby creating a file like this system/Tasks/Foo/Bar/BazTask.phpand adding it to the `<controller>` directory system/console.phpas follows:

use Inphinit\Experimental\Scheduling\Task; // The new Tasks\Foo\Bar\BazTask()->clear(); command will be executed $mytask = $scheduler->action('sample', 'Foo\\Bar\\BazTask::clear'); // Sets the task to be executed on the 1st of every month at 4:30 PM $mytask->cron(30, 16, 1, '*', '*'); // Sets the command to be executed in the background $mytask->runInBackground(true);

Since most methods return the class instance itself Inphinit\Experimental\Scheduling\Task, it's possible to use it like this:

use Inphinit\Experimental\Scheduling\Task; $scheduler ->action('sample', 'Foo\\Bar\\BazTask::clear') ->cron(30, 16, 1, '*', '*') ->runInBackground(true);