How to Run Asynchronous Tasks with Swoole’s Task Workers in PHP
This guide explains how to configure Swoole’s task worker pool, set the required onTask and onFinish callbacks, and use the non‑blocking task() method to dispatch long‑running operations without slowing down the server, complete with a full PHP example.
Swoole allows you to offload time‑consuming operations—such as broadcasting messages in a chat server or sending emails—from the main worker process by submitting them to a pool of task workers. The task() function is non‑blocking, returning immediately so the worker can continue handling new requests.
To use this feature you must configure the number of task workers with the task_worker_num setting and register the onTask and onFinish event callbacks on the server instance.
<?php
$serv = new Swoole\Server("127.0.0.1", 9501);
// Set the number of asynchronous task workers
$serv->set(array(
'task_worker_num' => 4
));
// Callback executed in the worker process when data is received
$serv->on('receive', function($serv, $fd, $from_id, $data) {
// Dispatch an asynchronous task
$task_id = $serv->task($data);
echo "Dispatch AsyncTask: id=$task_id
";
});
// Callback executed in a task worker process
$serv->on('task', function($serv, $task_id, $from_id, $data) {
echo "New AsyncTask[id=$task_id]";
// Return the result of the task
$serv->finish("$data -> OK");
});
// Callback executed in the worker process when a task finishes
$serv->on('finish', function($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});
$serv->start();The receive callback receives client data and immediately calls $serv->task($data) to hand the payload to a task worker. The task worker runs the onTask callback, processes the data, and calls $serv->finish() to send the result back. Finally, the onFinish callback runs in the original worker process, where you can handle the task’s outcome. Note that calling finish() is optional; a task can complete without returning a result.
After setting up the callbacks and starting the server with $serv->start(), the asynchronous task flow operates transparently, keeping the main request handling fast and responsive.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
