PHP code example of khoivan / laravel-async

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

    

khoivan / laravel-async example snippets


php artisan vendor:publish --provider="VXM\Async\AsyncServiceProvider" --tag="config"

return [
    /**
     * Maximum concurrency async processes.
     */
    'concurrency' => 20,

    /**
     * Async process timeout.
     */
    'timeout' => 15,

    /**
     * Sleep (micro-second) time when waiting async processes.
     */
    'sleepTime' => 50000,

    /**
     * An autoload script to boot composer autoload and Laravel application.
     * Default null meaning using an autoload of this package.
     */
    'autoload' => null,
];

use Async;

// run with anonymous function:
Async::run(function() {
    // Do a thing
});

// run with class@method
Async::run('Your\AsyncJobs\Class@handle');

// call default `handle` method if method not set.
Async::run('Your\AsyncJobs\Class');

use Async;

Async::run('Your\AsyncJobs\Class@jobA');
Async::run('Your\AsyncJobs\Class@jobB');
Async::run('Your\AsyncJobs\Class@jobC');
Async::run('Your\AsyncJobs\Class@jobD');

$results = Async::wait(); // result return from jobs above

use Async;

Async::run(function () {

    return 123;
}, [
    'success' => function ($output) { 
        // `$output` of job in this case is `123`.
    },
    'timeout' => function () { 
        // A job took too long to finish.
    },
    'error' => function (\Throwable $exception) {
        // When an exception is thrown from job, it's caught and passed here.
    },
]);

// Another way:
Async::run('AsyncJobClass@handleMethod', [
    'success' => 'AsyncJobEventListener@handleSuccess',
    'timeout' => 'AsyncJobEventListener@handleTimeout',
    'error' => 'AsyncJobEventListener@handleError'
]);

php artisan make:async-job MyJob

namespace App\AsyncJobs;

use App\MyModel;
use VXM\Async\Invocation;
use App\MyHandleDependency;
use Illuminate\Queue\SerializesModels;

class MyJob
{

    use Invocation;
    use SerializesModels;

    protected $model;
    
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(MyModel $model)
    {
        $this->model = $model;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(MyHandleDependency $dependency)
    {
        //
    }
}

use App\AsyncJobs\MyJob;
use App\MyHandleDependency;

$this->app->bindMethod(MyJob::class.'@handle', function ($job, $app) {
    return $job->handle($app->make(MyHandleDependency::class));
});

use Async;
use App\MyModel;
use App\AsyncJobs\MyJob;

$model = App\MyModel::find(1);

Async::run(new MyJob($model));