PHP code example of kage3f / rux-concorrency

1. Go to this page and download the library: Download kage3f/rux-concorrency 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/ */

    

kage3f / rux-concorrency example snippets


use function Rux\async;
use function Rux\sleep;
use function Rux\wait;

async(function() {
    echo "Task 1: Starting...\n";
    sleep(1000); // Non-blocking sleep
    echo "Task 1: Finished!\n";
});

async(function() {
    echo "Task 2: Starting...\n";
    sleep(500);
    echo "Task 2: Finished!\n";
});

wait(); // Execute the scheduler

use function Rux\async;
use function Rux\parallel_each;
use function Rux\wait;

async(function() use ($largeDataset) {
    // Processes the dataset using 10 concurrent workers
    parallel_each($largeDataset, function($chunk) {
        $db = getDbConnection();
        foreach ($chunk as $item) {
            $db->prepare("INSERT INTO table ...")->execute($item);
            \Rux\sleep(0); // Optional: yield to other tasks
        }
    }, concurrency: 10);
});

wait();

use function Rux\async;
use function Rux\await;
use function Rux\wait;

async(function() {
    $task1 = async(fn() => "Data from API 1");
    $task2 = async(fn() => "Data from API 2");

    // Suspends this fiber until the tasks are finished
    $res1 = await($task1);
    $res2 = await($task2);

    echo "$res1, $res2\n";
});

wait();

use function Rux\async;
use function Rux\get_json;
use function Rux\wait;

async(function() {
    try {
        $data = get_json('https://api.example.com/data');
        print_r($data);
    } catch (\Exception $e) {
        echo "Error: " . $e->getMessage();
    }
});

wait();