Purpose
In modern web applications, handling long-running tasks synchronously can cause delays for users and slow down the frontend experience. Using workers allows us to offload these processes into the background, improving responsiveness while completing complex actions asynchronously.
Use Case
- Keeps the frontend responsive and fast by delegating time-consuming processes.
- Improves user experience, especially during resource-heavy actions like user creation, data synchronization, and external API calls.
- Provides a structure for scalable task management in e-commerce systems.
Challenges
When implementing workers, one key challenge is passing data between the synchronous trigger point and the asynchronous worker process. This requires structured data serialization so the worker can later reconstruct and process the information accurately.
Implementation Example: Asynchronous Checkout Process
AfterCheckoutExample.php
namespace TS\Example\Modules;
use TS\Example\Modules\Tasks\ExampleWorker;
class AfterCheckoutExample {
public function __construct() {
add_action('woocommerce_checkout_order_processed', [$this, 'queue_example_worker'], 10, 1);
}
public function queue_example_worker($order_id) {
$order = wc_get_order($order_id);
$data = [
'email' => $order->get_billing_email(),
'first_name' => $order->get_billing_first_name(),
'last_name' => $order->get_billing_last_name(),
];
$worker = new ExampleWorker();
$worker->push_to_queue($data)->save()->dispatch();
}
}
new AfterCheckoutExample();
ExampleWorker.php
namespace TS\Example\Modules\Tasks;
use TS\WonderfulRelations\Modules\Worker\BaseClass\WR_Worker;
class ExampleWorker extends WR_Worker {
protected $action = "ExampleWorker";
protected function task($data) {
error_log("Processing data for: " . print_r($data, true));
sleep(5); // Simulate a delay
// Example action
$this->log_user_creation($data);
}
private function log_user_creation($data) {
error_log("User created: " . $data['email']);
}
}
new ExampleWorker();