How to execute functions asynchronously with SWOOLE?

608 Views Asked by At

I have heard promising words about php's Swoole project. However, in their doc/examples, I only see the implementation of server handlings (i.e. how to setup webserver, answer requests, etc..). However, I was unable to find examples, how to simply fire an asynchronous functions from cli (i.e. php myfile.php) where myfile.php might contain (with my undestranding) something like this Swoole\SomeAsyncFunion (just phseudo name):

Swoole\SomeAsyncFunion(  function(){ file_get_contents("http://site-1.com"); echo "hello";  }   );
Swoole\SomeAsyncFunion(  function(){ do_long_running_function(); echo "world"; }   ); 
Swoole\SomeAsyncFunion( .... ); 
Swoole\SomeAsyncFunion( .... ); 
Swoole\SomeAsyncFunion( .... ); 

So, just execute multiple functions in async from php-cli. How to do that? With parallel extension I exactly same as described ( \parallel\run( function(){ ... } ); ) but couldn't figure-out how to do with swoole. (i dont have a requirement of any web-server, just need cli).

1

There are 1 best solutions below

0
On

you can use Co\run and go

use function Swoole\Coroutine\go;
use function Swoole\Coroutine\run;

run(function () {
    go(function () {
        file_get_contents("http://site-1.com"); echo "hello";
    });
    go(function () {
        do_long_running_function(); echo "world";
    });
});