PHP code example of pfinalclub / asyncio

1. Go to this page and download the library: Download pfinalclub/asyncio library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pfinalclub / asyncio example snippets



function PfinalClub\Asyncio\{run, sleep};

run(function() {
    echo "Hello, ";
    sleep(1);  // Non-blocking sleep
    echo "AsyncIO v3.0!\n";
});

use function PfinalClub\Asyncio\{run, create_task, gather, sleep};
use PfinalClub\Asyncio\Concurrency\{CancellationScope, TaskGroup};

run(function() {
    // All tasks are automatically scoped
    $scope = CancellationScope::current();
    
    $task1 = create_task(function() {
        sleep(1);
        return "Task 1 completed";
    });
    
    $task2 = create_task(function() {
        sleep(1);
        return "Task 2 completed";
    });
    
    // Wait for all tasks - completes in ~1s, not 2s!
    $results = gather($task1, $task2);
    print_r($results);
});

use function PfinalClub\Asyncio\{run, create_task, gather, set_context, get_context};

run(function() {
    // Set request context
    set_context('request_id', uniqid('req_'));
    set_context('user_id', 12345);
    
    $tasks = [];
    for ($i = 0; $i < 10; $i++) {
        $tasks[] = create_task(function() use ($i) {
            // Auto-inherit parent context
            $requestId = get_context('request_id');
            $userId = get_context('user_id');
            
            echo "Task {$i}: Request {$requestId}, User {$userId}\n";
        });
    }
    
    gather(...$tasks);
});

// Task Management
create_task(callable $callback, string $name = ''): Task
run(callable $main): mixed
await(Task $task): mixed
gather(Task ...$tasks): array
wait_for(callable|Task $awaitable, float $timeout): mixed

// Timing
sleep(float $seconds): void
get_event_loop(): EventLoop

// Concurrency
semaphore(int $max): Semaphore

// Context Management
set_context(string $key, mixed $value): void
get_context(string $key, mixed $default = null): mixed
has_context(string $key): bool
delete_context(string $key): void
get_all_context(bool $

// ❌ Removed from core package
use PfinalClub\Asyncio\Production\HealthCheck;
use PfinalClub\Asyncio\Production\GracefulShutdown;
use PfinalClub\Asyncio\Production\MultiProcessMode;
use PfinalClub\Asyncio\Production\ResourceLimits;

// ✅ Install separate package
composer 

// ❌ Removed (use gather instead)
wait_first_completed()
wait_all_completed()

// ❌ Removed (use try/catch instead)
shield()

// ✅ Still available
create_task()
run()
await()
gather()
wait_for()

// ✅ All core APIs still work
run(function() {
    $task = create_task(function() {
        return "Hello v3.0";
    });
    
    $result = await($task);
    echo $result;
});