Plugin Development: Background Jobs

Previous Section: Scheduled Tasks


If your plugin needs to perform a one-off task that is not time-sensitive, such as in response to an event or action, you can dispatch a background job to run it on a queue. The job is processed by a queue worker in the background, so slow work like calling an external API is moved out of the web request and does not have to wait for a scheduled time.

Why Use a Background Job?

Background jobs let you run a one-off task outside of the web request, keeping the request fast. Unlike a scheduled task, which runs on a recurring schedule, a job is dispatched only when needed. Example cases where this is useful:

  • Sync a user or ticket to an external system after it has been created or updated
  • Process a large number of records after an operator action, without making them wait for it to complete

Jobs are processed by the queue workers run from the cron job, or by Horizon on Docker deployments. How soon a job starts depends on how the queue workers are run and how many jobs are already queued, so jobs should only be used for tasks that are not time-sensitive.

If the task needs to run at a regular interval rather than in response to something happening, use a scheduled task instead.

Choosing a Queue

SupportPal runs two queues, and your job should extend the matching base class.

  • \App\Modules\Core\Controllers\Queues\Job - the default queue, for jobs that complete in a few seconds.
  • \App\Modules\Core\Controllers\Queues\SlowJob - the slow queue, for jobs that may take minutes to complete (up to a 15 minute timeout). Using the slow queue prevents long-running work from delaying time-sensitive jobs.

Writing a Job

A job is a class with a handle method containing the work to perform. Any data the job needs should be passed to the constructor, which must call the parent constructor so the job is placed on the correct queue. Eloquent models passed to the constructor are automatically serialized and re-fetched when the job runs.

Jobs/SyncUser.php

    <?php

    namespace Addons\Plugins\HelloWorld\Jobs;

    use App\Modules\Core\Controllers\Queues\SlowJob;
    use App\Modules\User\Models\User;

    class SyncUser extends SlowJob
    {
        public function __construct(public readonly User $user)
        {
            parent::__construct();
        }

        public function handle(): void
        {
            // Run our job code
        }
    }

If the job fails, it should throw an exception. The job is then marked as failed and the error is written to the application log files.

Dispatching a Job

Use the static dispatch method to push the job on to its queue. The arguments are passed to the job's constructor.


    \Addons\Plugins\HelloWorld\Jobs\SyncUser::dispatch($user);

The job then waits on the queue until a queue worker picks it up and runs its handle method.


Next Section: Sending Email