~/docs
Resonate
Resonate
2.x 2.4.0, current
Torque
Toggle sidebar
Torque
webpatser/torque 2.4.0

Torque 2.x

Examples

Complete examples for async jobs, progress events, programmatic streams, alerts and per-stream settings.

Async job with pools

A TorqueJob that reads from MySQL and writes to an HTTP endpoint without blocking the worker. MysqlPool needs a connection string, so bind it once in a service provider (HttpPool resolves on its own):

use Webpatser\Torque\Pool\MysqlPool;
 
// In a service provider's register() method
$this->app->singleton(MysqlPool::class, fn () => new MysqlPool('host=127.0.0.1 user=app password=secret db=app', 20));

The job:

use Webpatser\Torque\Job\TorqueJob;
use Webpatser\Torque\Pool\MysqlPool;
use Webpatser\Torque\Pool\HttpPool;
 
class IndexDocument extends TorqueJob
{
public function __construct(
private int $documentId,
) {}
 
public function handle(MysqlPool $db, HttpPool $http): void
{
$result = $db->execute('SELECT * FROM documents WHERE id = ?', [$this->documentId]);
$row = $result->fetchRow();
 
$response = $http->post('http://elasticsearch:9200/docs/_doc/' . $this->documentId, json_encode($row));
}
}

Dispatch it like any job:

IndexDocument::dispatch($documentId)->onQueue('high');

Progress events

Emit progress from inside a job, then tail it. emit() needs InteractsWithQueue so the job instance is set:

use Illuminate\Bus\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Webpatser\Torque\Stream\Streamable;
 
class ImportCsv implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, Streamable;
 
public function handle(): void
{
foreach ($this->rows as $i => $row) {
// process...
$this->emit("Imported row {$i}", progress: $i / count($this->rows));
}
}
}
php artisan torque:tail --job=088066c1-b045-4fb6-bc32-ca15cfdf7d08

Read a job stream in code

use Webpatser\Torque\Stream\JobStream;
 
$stream = app(JobStream::class);
 
// All events so far
$events = $stream->events($uuid);
 
// Tail (blocks, yields events as they arrive)
foreach ($stream->tail($uuid) as $event) {
echo $event['type'] . ': ' . ($event['data']['message'] ?? '');
}
 
// Check completion
$stream->isFinished($uuid); // true after completed/failed

Per-job isolated state

use Webpatser\Torque\Job\CoroutineContext;
 
// Inside a job handler
CoroutineContext::set('tenant_id', $this->tenantId);
$tenantId = CoroutineContext::get('tenant_id');

Long-wait alerts

In config/torque.php:

'waits' => ['emails' => 60],

In a service provider:

use Webpatser\Torque\Torque;
 
Torque::routeMailNotificationsTo('[email protected]');
Torque::routeSlackNotificationsTo($webhookUrl);

Alert on permanent failures

use Webpatser\Torque\Events\JobPermanentlyFailed;
 
Event::listen(JobPermanentlyFailed::class, function ($event) {
// $event->jobName, $event->queue, $event->exceptionMessage, etc.
Notification::route('slack', '#alerts')->notify(new YourNotification($event));
});

Circuit breaker per stream

'streams' => [
'scrpr' => ['circuit_breaker' => ['threshold' => 0.8, 'cooldown' => 600]],
'mail' => ['circuit_breaker' => false],
],

Dashboard gate and CSP nonce

Gate::define('viewTorque', fn (User $user) => $user->isAdmin());
 
\Webpatser\Torque\Torque::cspNonce($nonce);

Deploy script reload

# Deployer's run() defaults to a 300s timeout; keep the reload inside it.
php artisan torque:reload --drain --if-running --timeout=240