• Services

Queuing tasks

Includable comes with a built-in way to execute background tasks, in order to expedite certain actions to make user interaction faster. This happens through the Queue class and a custom controller named queue.

Listening for tasks

First, add a new controller called queue to your module.json file:


{
    "controllers": {
        "web": "web/index.php",
        "queue": "queue.php"
    },
    ...
}

This file can contain any code, and will be executed when the application starts on the Includable servers. Note that the file itself should not do anything on execution, other than add queue handlers. This is done in the following fashion:

queue.php

<?php

Queue::listen('greet', function($data) {
    dd('Hey ' . $data['name'] . '!');
});

Dispatching tasks

Now that we have our task called 'greet' up and running, let's execute it from our web controller:

web/index.php

<?php

Queue::dispatch('greet', ['name' => 'Thomas']);

echo 'Dispatched!';

If you now run your module using the inc run command in your console, you should see something like this in the output:

Queue Added queue message: 08116178-016b-41c4 (module934.greet) 02:31:45
Logger INFO Hey Thomas! 02:31:46

That means you just executed your first queue task!

Some details about queue tasks

  • The second parameter of dispatch() accepts any type of PHP object, but the standard is to pass data for the tasks as an array.
  • Queue tasks are executed without knowing about communities or users. So if you want to do something with a specific community or user, you have to pass the ID of that resource through to the task using the $data parameter.
  • Queue tasks are executed exactly once, but are distributed across several servers. That means that a queue task scheduled on one server might be executed on another. So you can not rely on any stored files in your task without downloading them first at the beginning of the task.
  • Class BatchJob makes it easy to create a group of jobs and keep track of their progress.