Background Tasks Example

Patterns for running work after sending a response.

Run

pagi-server --app examples/background-tasks/app.pl --port 5000

Watch the server console for background task output.

Patterns

1. Async I/O (Non-Blocking)

For network calls, database queries, file I/O using async libraries:

fire_and_forget(send_welcome_email($email));

Always use ->on_fail() before ->retain() to avoid silently swallowing errors.

2. Blocking/CPU Work (Subprocess)

For CPU-intensive or blocking operations, use IO::Async::Function:

run_blocking_task("heavy_computation", 3);

Runs in a child process, doesn't block the event loop.

3. Quick Sync Work

For very fast operations (<10ms) after response:

$res->loop->later(sub { quick_sync_task("log"); });

Warning: Any blocking here blocks ALL requests!

Endpoints