PHP code example of morningtrain / wp-async

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

    

morningtrain / wp-async example snippets


\Morningtrain\WP\Async\Async::registerWorker();

use Morningtrain\WP\Async\Abstracts\AbstractAsyncTask;

class TestTask extends AbstractAsyncTask {
    public static function handle($arg1, $arg2) {
        // Do something;
        return "$arg1 $arg2";
    }
}

TestTask::dispatch('arg1', 'arg2');

TestTask::dispatchBlocking('arg1', 'arg2');

public static function dispatchBlocking(mixed ...$params) :array|WP_Error
{
    return static::getWorker()->dispatchBlockingTask(static::getCallback(), $params, 30);
}

use Morningtrain\WP\Async\Abstracts\AbstractAsyncTask;

class TestTask extends AbstractAsyncTask {
    public static function handle($arg1, $arg2) {
        // Do something;
        
        $somethingWentWrong = true;
        
        if ($somethingWentWrong) {
            return new \WP_Error('something_went_wrong', 'Something went wrong');
        }
        
        return "$arg1 $arg2";
    }
}

use Morningtrain\WP\Async\Abstracts\AbstractAsyncTask;
use Exception;

class TestTask extends AbstractAsyncTask {
    public static function handle($arg1, $arg2) {
        // Do something;
        
        $somethingWentWrong = true;
        
        if ($somethingWentWrong) {
            throw new Exception('Something went wrong');
        }
        
        return "$arg1 $arg2";
    }
}

use Morningtrain\WP\Async\Abstracts\AbstractAsyncTask;

class TestTask extends AbstractAsyncTask {
    public static function handle($arg1, $arg2) {        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('You are not allowed to do this!', 401);
            exit;
        }
        
        // Do something;
        
        return "$arg1 $arg2";
    }
}