PHP code example of krypt0nn / asynclib

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

    

krypt0nn / asynclib example snippets




synclib\TaskRunner;

return new TaskRunner (function (array $options, TaskRunner $task)
{
    // your task code goes here
});



synclib\Task;

// Create new task from file
// and run it

$task = Task::create ('path/to/task/file.php')->run ([
    // here you can write some options
    // that will be available in TaskRunner
    // also you can run this method
    // without any arguments
]);

/**
 * Task state
 * null  - task is not initialized
 * false - task is still running
 * true  - task is done and you can get its output
 */
$state = $task->update ();

// PHP 8 syntax
$task->wait (milliseconds: 5000);

$task->wait (delay: 1000, callable: function ()
{
    echo 'Task is not finished yet' . PHP_EOL;
});

$task->on ('some_event', function ($data, Task $task)
{
    echo 'Hey! I got a message from task: '. $data . PHP_EOL;
});



synclib\TaskRunner;

return new TaskRunner (function (array $options, TaskRunner $task)
{
    for ($i = 0; $i < 5; ++$i)
    {
        // Performing event "some_event"
        // in main process
        $task->perform ('some_event', 'Now I am at position '. ($i + 1));

        sleep (1);
    }
});

$task->onFinished (function ($output, Task $task)
{
    echo 'Hey! Task with id '. $task->id() .
        ' seems to be finished with output: '. $output . PHP_EOL;
});

$task->stop ();



synclib\Pool;

// Create tasks pool
$pool = Pool::create ([
    'path/to_some_task.php',
    'path/to_some_another_task.php',

    Task::create ('or_the_task/itself.php')->onFinished (function ($output)
    {
        echo 'Task finished with output: '. $output . PHP_EOL;
    })
]);

// Run pool execution
$pool->run ();

// Wait untill all tasks in this pool will be finished
$pool->updateWhileExist ();

$task_output = $pool->output ('task_id');

$pool->add (Task::create ('path_to_task.php'));