Run PHP Task Asynchronously

Run PHP Task Asynchronously

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Run PHP Task Asynchronously

Handling long-running operations in a synchronous web request is a classic architectural challenge. When a user hits "Finish Registration," your application shouldn't block the thread to wait for an SMTP transaction to complete or a file to process. Blocking forces the user to stare at a loading spinner, increasing bounce rates and degrading perceived performance. The goal is to initiate the work and immediately return control to the request handler.

While exec() offers a quick workaround by spawning a child process in the background, it introduces significant operational friction. As demonstrated in patterns like exec("doTask.php ... &"), this approach bypasses standard framework lifecycle events. If your application relies on service containers or middleware that expect to be invoked during the request cycle, those hooks simply won't run for the backgrounded task. Furthermore, debugging becomes a nightmare; if doTask.php fails silently in the background, you have no centralized log output unless you explicitly configure one within that isolated file.

A more robust pattern involves decoupling the execution of the task from the request itself using a dedicated worker process. Your proposed solution of queuing tasks in a MySQL table and polling for them is a valid implementation of the "Task Queue" pattern, often associated with frameworks like Laravel Horizon or Symfony ProcessMaker. However, polling a database once per second is generally inefficient. A better approach is to use an event-driven model where the worker listens for new records rather than actively checking for them in a loop.

To implement this effectively without reinventing the wheel, consider using a persistent job queue driver. If you are working within the Laravel ecosystem, the built-in Queue component supports databases, Redis, and SQS out of the box. You can define a Job class that encapsulates the logic for sending the welcome email. When the controller detects the need for an asynchronous action, it dispatches the job to the queue rather than executing it immediately.

Here is how you might structure the dispatch in a controller:

use App\Jobs\SendWelcomeEmail;
use Illuminate\Support\Facades\Queue;

public function register(Request $request)
{
    // ... perform registration logic ...

    Queue::push(new SendWelcomeEmail($user->id), 'emails');
    
    return response()->json(['status' => 'success']);
}

On the infrastructure side, you need a separate process to consume these jobs. This can be a long-running CLI command that never exits:

php artisan queue:work --sleep=3 --timeout=90 --max-time=3600

This command runs indefinitely, fetching jobs from the jobs table (or Redis) and executing them. The worker handles failures gracefully by pushing failed jobs back onto the queue after a retry interval, ensuring that transient network errors don't lose data.

The trade-off here is complexity versus control. By moving to a queue system, you gain the ability to scale workers horizontally. If your application grows, you can spin up additional worker processes on separate machines to handle the load without touching the web server code. You also gain visibility into job throughput and failure rates through monitoring tools.

However, this approach requires managing a separate process and ensuring it stays alive. It adds configuration overhead compared to a simple exec() call, but the reliability gains are substantial. The database queue pattern is particularly useful if you want to persist jobs across server restarts or need to inspect them manually in a debugging scenario.

Ultimately, the choice depends on your current stack. If you are already using a framework with native queue support, leveraging that abstraction layer is almost always superior to writing custom polling scripts or managing backgrounded exec() calls manually.

Our network