Swoole server methods list

Table of Contents

public void Swoole\Server::addlistener ( string $host , integer $port , string $socket_type )

Alias: swoole_server->addListener( string $host , integer $port , string $socket_type )

<?php
mixed swoole_server->addListener(string $host, int $port, $type = SWOOLE_SOCK_TCP);

Add more listening IP or port for the server. The connection information can be acccessed by $server->connection_info() when the server has started. By the connection information, you can distinguish the source port of the connection.

Parameters

  • $host: the ip address of the server
  • $port: the port of the server

    • it needs root privileges if the port is litte than 1024
    • the parameter $port will be ignored when the parameter $sock_type is setted to SWOOLE_UNIX_DGRAM or SWOOLE_UNIX_STREAM
    • if the parameter $port is setted to 0, the swoole server would use a random and available port
  • $sock_type: the socket type of the server:

    • SWOOLE_SOCK_TCP: TCP
    • SWOOLE_SOCK_TCP6: TCP IPv6
    • SWOOLE_SOCK_UDP: UDP
    • SWOOLE_SOCK_UDP6: UDP IPv6
    • SWOOLE_UNIX_DGRAM: Unix socket dgram
    • SWOOLE_UNIX_STREAM: Unix socket stream
  • Enable SSL: $sock_type | SWOOLE_SSL. To enable ssl, it must set the configuration about ssl.

Return

The swoole_server_port object

Example

<?php
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
$server->addlistener("192.168.1.100", 9503, SWOOLE_SOCK_TCP);
$server->addlistener("0.0.0.0", 9504, SWOOLE_SOCK_UDP);
//UnixSocket Stream
$server->addlistener("/var/run/myserv.sock", 0, SWOOLE_UNIX_STREAM);
//TCP + SSL
$server->addlistener("127.0.0.1", 9502, SWOOLE_SOCK_TCP | SWOOLE_SSL); 
//Listen on a random port
$port = $server->addListener("0.0.0.0", 0, SWOOLE_SOCK_TCP);
echo $port->port;

public boolean Swoole\Server::addProcess ( swoole_process $process )

Alias: swoole_server->addProcess( swoole_process $process )

<?php
bool swoole_server->addProcess(swoole_process $process)

Add a user defined child process to the server. The process can be used as monitoring or other tasks.

Parameter

Return

The return value indicates the result of add proccess to swoole server.

Example:
<?php
$server = new swoole_server('127.0.0.1', 9501);

$process = new swoole_process(function($process) use ($server) {
    while (true) {
        $msg = $process->read();
        foreach($server->connections as $conn) {
            $server->send($conn, $msg);
        }
    }
});

$server->addProcess($process);

$server->on('receive', function ($serv, $fd, $from_id, $data) use ($process) {
    // send the data received to all the child processes
    $process->write($data);
});

$server->start();

public ReturnType Swoole\Server::after ( integer $after_time_ms , callable $callback [, string $param ] )

Alias: swoole_server->after( integer $after_time_ms , callable $callback [, string $param ] )

int swoole_server->after(int $after_time_ms, mixed $callback_function)

Trigger a one time tick in the future. Alias of function swoole_timer_after(). You can remove the timer later by calling swoole_timer_clear

Parameter

  • $time the number of millisecond
  • $callable the function that triggered after with a fixed time delay

Return

the timer id which uniquely identifies the timer

Example

public boolean Swoole\Server::bind ( integer $fd , integer $uid )

Alias: swoole_server->bind( integer $fd , integer $uid )

<?php
bool swoole_server->bind(int $fd, int $uid)

Bind the fd with system user UID.

The dispatch of different socket connection to the swoole server is influenced by the configuration of dispatch_mode

In the default dispatch_mode which is 2, the socket connection may be dispatched to different worker process after reconnetion. You can set the configuration of dispatch_mode to 5 and call swoole_server->bind to bind a uid number to socket connection. And then the same uid socket connection will be dispatched to the same worker process.

Parameter

  • $fd the id number of client
  • $uid the uid number binded for the client

Return

The result of binding

Example

public void Swoole\Server::clearTimer ( integer $timer_id )

Alias: swoole_server->clearTimer( integer $timer_id )

<?php
void swoole_server->clearTimer(int $timer_id)

Cancel the timer tick or one time tick. Alias of function swoole_timer_clear.

Parameter

  • $timer_id the number of timer id which uniquely identifies a timer

Return

void

Example

$timer_id = $server->tick(1000, function ($id) use ($server) {
    $server->clearTimer($id);
});

public bool Swoole\Client::close ([ bool $force ] )

Alias: swoole_server->close([ bool $force ] )

Close the connection to the remote TCP socket and emit Close event.

Parameter

  • $fd the id of connection between the server and the client
  • $reset if close the connection forcibly and loose the data of this connection

Return

the result of close the connection

Example

public array Swoole\Server::connection_info ( integer $fd [, integer $reactor_id ] )

Alias: swoole_server->connection_info( integer $fd [, integer $reactor_id ] )

Prototype

<?php
mixed swoole_server->connection_info(int $fd, int $from_id, bool $ignore_close = false)

Get the connection info, alias of function swoole_server->getClientInfo().

Parameter

  • $fd the id number of client
  • $from_id this parameter is needed, the swoole server is type of UDP
  • $ignore_close this method will return the information of connection even if the connection is closed

Return

The array of information of the $fd client

if the $fd client dosen't exist, the result is false

Example

<?php
$fdinfo = $serv->connection_info($fd);
var_dump($fdinfo);
array(5) {
  ["from_id"]=>
  int(3)
  ["server_fd"]=>
  int(14)
  ["server_port"]=>
  int(9501)
  ["remote_port"]=>
  int(19889)
  ["remote_ip"]=>
  string(9) "127.0.0.1"
  ["connect_time"]=>
  int(1390212495)
  ["last_time"]=>
  int(1390212760)
}

$udp_client = $serv->connection_info($fd, $from_id);
var_dump($udp_client);

public array Swoole\Server::connection_list ( integer $start_fd [, integer $pagesize ] )

Alias: swoole_server->connection_list( integer $start_fd [, integer $pagesize ] )

Get the list of all the TCP connections for all the workers.

this method is besed on the shared memory and is fast.

Parameter

  • $start_fd the start id number of client list
  • $pagesize the pagesize of list

Return

The array list of the $fd client

If fail, the result is FALSE.

Example

<?php
$start_fd = 0;
while(true)
{
    $conn_list = $serv->connection_list($start_fd, 10);
    if($conn_list===false or count($conn_list) === 0)
    {
        echo "finish\n";
        break;
    }
    $start_fd = end($conn_list);
    var_dump($conn_list);
    foreach($conn_list as $fd)
    {
        $serv->send($fd, "broadcast");
    }
}

public Swoole\Server::__construct ( string $host [, integer $port [, integr $mode [, integer $sock_type ]]] )

Alias: swoole_server::__construct ( string $host [, integer $port [, integr $mode [, integer $sock_type ]]] )

Construct a swoole server object

Parameter

  • $host: the ip address of the server
  • $port: the port of the server (it needs root privileges if the port is litte than 1024)
  • $mode: the running mode of the server:
    • SWOOLE_PROCESS: multiple process mode, the business logic is running in child processes, the default running mode of server
    • SWOOLE_BASE: reactor based mode, the business logic is running in the reactor
  • $sock_type: the socket type of the server:
    • SWOOLE_SOCK_TCP: TCP
    • SWOOLE_SOCK_TCP6: TCP IPv6
    • SWOOLE_SOCK_UDP: UDP
    • SWOOLE_SOCK_UDP6: UDP IPv6
    • SWOOLE_UNIX_DGRAM: Unix socket dgram
    • SWOOLE_UNIX_STREAM: Unix socket stream
  • Enable SSL: $sock_type | SWOOLE_SSL. To enable ssl, it must set the configuration about ssl.

Return

The swoole_server object

Example:

Listen on a random port:

The swoole supports the feature of listening on a random port. When the argument $port isn't seted or is 0, the swoole will choose a random and available port to listen on. You can use $server->port to listen on.

<?php
$http = new swoole_http_server("127.0.0.1");

$http->on('request', function ($request, $response) {
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});

$http->start();
Listen on a port defined in systemd

The swoole-1.9.7 adds the support for systemd socket. The port listened on can be setted by the configuration of systemd.

swoole.socket

[Unit]
Description=Swoole Socket

[Socket]
ListenStream=9501
Accept=false
[Install]
WantedBy = sockets.target

swoole.service

[Service]
Type=forking
PIDFile=/var/run/swoole.pid
ExecStart=/usr/bin/php /var/www/swoole/server.php
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID

[Install]
WantedBy = multi-user.target

server.php

$http = new swoole_http_server("systemd");

$http->set([
    'daemonize' => true,
    'pid_file' => '/var/run/swoole.pid',
]);

$http->on('request', function ($request, $response) {
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});

$http->start();

Start the systemd service

sudo systemctl enable swoole.socket
sudo systemctl start swoole.socket
sudo systemctl start swoole.service

public void Swoole\Server::defer ( callable $callback )

Alias: swoole_server->defer( callable $callback )

Delay execution of the callback function at the end of current EventLoop. Alias of function swoole_event_defer().

Parameter

  • $callback the function that defers to execute

Return

void

Example

function query($server, $db) {
    $server->defer(function() use ($db) {
        $db->close();
    });
}

public boolean Swoole\Server::exist ( integer $fd )

Alias: swoole_server->exist( integer $fd )

Check whether the $fd which indicates a TCP client is existed.

Parameter

  • $fd the id number of client

Return

the existence of $fd client

Example

public void Swoole\Server::finish ( string $data )

Alias: swoole_server->finish( string $data )

Used in task process for sending result to the worker process when the task is finished.

Parameter

  • $data the data to send to the worker process

Return

Example

public integer Swoole\Server::getLastError ( void )

Alias: swoole_server->getLastError()

Get the error code of the most recent error.

Parameter

void

Return

The error code

Error codes:

  • 1001: The connection has been closed by the server.
  • 1002: The connection has been closed by the client side.
  • 1003: The connection is closing.
  • 1004: The connection is closed.
  • 1005: Error $fd.
  • 1007: Received data after connection has been closed.
  • 1008: The send buffer is full.

Example

public mixed Swoole\Server::getLastError()

Alias: swoole_server->getSocket()

Prototype

resource swoole_server->getSocket()

Get socket and update the options of the socket.

This method is based on the extension sockets and it needs to add the compiling configuration --enable-sockets

Parameter

void

Return

The handler of sockets resource

Example

<?php
$socket = $server->getSocket();
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

Multi cast example:

<?php
$server = new swoole_server('0.0.0.0', 9905, SWOOLE_BASE, SWOOLE_SOCK_UDP);
$server->set(['worker_num' => 1]);
$socket = $server->getSocket();

$ret = socket_set_option(
    $socket,
    IPPROTO_IP,
    MCAST_JOIN_GROUP,
    array('group' => '10.0.0.5', 'interface' => 'eth0')
);

if ($ret === false)
{
    throw new RuntimeException('Unable to join the multicast group');
}

$server->on('Packet', function (swoole_server $serv, $data, $addr)
{
    $serv->sendto($addr['address'], $addr['port'], "Swoole: $data");
    var_dump( $addr, strlen($data));
});

$server->start();

public mixed Swoole\Server::heartbeat ( boolean $if_close_connection )

Alias: swoole_server->heartbeat( boolean $if_close_connection )

Check status of all the connections of the server. Optionally close the idle and timeout connections.

Parameter

  • $if_close_connection the option which decides if close the connections which exceeds the time

Return

The array of connections

Example

public boolean Swoole\Server::listen ( string $host , integer $port , string $socket_type )

Alias: swoole_server->listen( string $host , integer $port , string $socket_type )

Alias of bool swoole_server->addlistener(string $host, int $port, int $type);

public void Swoole\Server::on ( string $event_name , callable $callback )

Alias: swoole_server->on ( string $event_name , callable $callback )

Register callback function for the event

Parameter

  • $event the string of event to be registered
  • $callback the callable type variable

Check the full list of events

Check the four types of callbacks

Return

The result if it has been registered successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public void Swoole\Server::pause ( integer $fd )

Alias: swoole_server->pause( integer $fd )

Pause the data receiving for the $fd client.

Only available in SWOOLE_BASE mode.

Parameter

  • $fd the id number of client

Return

The result of pausing

Example

public void Swoole\Server::protect ( integer $fd [, boolean $is_protected ] )

Alias: swoole_server->protect( integer $fd [, boolean $is_protected ] )

Protect the $fd from being closed by the thread of checking heart beat

Parameter

  • $fd the id number of client
  • $value if true, protect the $fd. If false, remove the protect from $fd

Return

Example

public boolean Swoole\Server::reload ( void )

Alias: swoole_server->reload()

Gracefully restart all the worker processes and reload the PHP files.

  • The reload only works for the files included after onWorkerStart and onReceive, and not for the files included before the start of the swoole_server
  • The reload not works for the runtime setting of the swoole server. The runtime setting should be changed by the restart of swoole server

Parameter

  • $only_reload_taskworkrer if the call of reload only reloads taskworkrer

Return

The result if it has been reloaded successfully

Example

Restart all the worker processes by signal

kill -USR1 MASTER_PID

Only restart the task processes by signal

kill -USR2 MASTER_PID

Get all the files loaded before the worker started

<?php
$server->on('WorkerStart', function($serv, $workerId) {
    var_dump(get_included_files());
});

When using APC/OpCache

  • stat in APC/OpCache has to be enabled for code reload
  • Refresh OpCache with apc_clear_cache() or opcache_reset() if necessary

public void Swoole\Server::resume ( integer $fd )

Alias: swoole_server->resume( integer $fd )

Resume the data receiving for the $fd client..

Only available in SWOOLE_BASE mode.

Parameter

  • $fd the id number of client

Return

The result of resuming

Example

public boolean Swoole\Server::send ( integer $fd , string $data [, integer $reactor_id ] )

Alias: swoole_server->send( integer $fd , string $data [, integer $reactor_id ] )

Send data to the remote TCP socket.

Parameter

  • $fd the id number of client
  • $data the function that triggered after with a fixed time delay
  • $extraData the extra data of sending data

Return

the result of send data to the client

If the result is false, you can call the method $server->getLastError() to get the error code.

Example

public boolean Swoole\Server::sendMessage ( integer $worker_id , string $data )

Alias: swoole_server->sendMessage( integer $worker_id , string $data )

Send message to worker processes by ID. This message will trigger the event of pipe message and the process which has received this message would call the callback function registered for pipe message.

There is no length limit for the message, but the server will use the temporary file in the memory if the length of file is bigger than 8K In the task worker process, sendMessage is blocking In the worker process, sendMessage is async.

Parameter

  • $message the string of message to send
  • $dst_worker_id the integer of worker process which is between 0 and (worker_num + task_worker_num - 1)

Return

The result of send message to worker

Example

<?php
$serv = new swoole_server("0.0.0.0", 9501);
$serv->set(array(
    'worker_num' => 2,
    'task_worker_num' => 2,
));
$serv->on('pipeMessage', function($serv, $src_worker_id, $data) {
    echo "#{$serv->worker_id} message from #$src_worker_id: $data\n";
});
$serv->on('task', function ($serv, $task_id, $from_id, $data){
    var_dump($task_id, $from_id, $data);
});
$serv->on('finish', function ($serv, $fd, $from_id){

});
$serv->on('receive', function (swoole_server $serv, $fd, $from_id, $data) {
    if (trim($data) == 'task')
    {
        $serv->task("async task coming");
    }
    else
    {
        $worker_id = 1 - $serv->worker_id;
        $serv->sendMessage("hello task process", $worker_id);
    }
});

$serv->start();

public boolean Swoole\Server::sendfile ( integer $fd , string $filename [, integer $offset ] )

Alias: swoole_server->sendfile( integer $fd , string $filename [, integer $offset ] )

Send large size data or files to the remote TCP socket. A wrapper of the sendfile system call.

Parameter

  • $fd the id number of client
  • $filename the path of file to send
  • $offset the start offset of file to send. The default of this parameter is 0
  • $length the length of file to send. The default of this parameter is the whole length of file

Return

The timer id which uniquely identifies the timer

Example

<?php
$server->sendfile($fd, __DIR__.'/test.jpg');

public boolean Swoole\Server::sendto ( string $ip , integer $port , string $data [, string $server_socket ] )

Alias: swoole_server->sendto( string $ip , integer $port , string $data [, string $server_socket ] )

Send data to the remote UDP address.

To use swoole_server->sendto, the swoole server has to listen the port of UDP To use swoole_server->sendto to send data to IPV6, the swoole server has to listen the port of UDP6

Parameter

  • $ip the string of ip address
  • $port the integer of port
  • $data the data to send
  • $server_socket the swoole server may listen multiple port at the same time, use $server_socket to assign the port to use

Return

The result of send data

Example

<?php
$server->sendto('220.181.57.216', 9502, "hello world");

$server->sendto('2600:3c00::f03c:91ff:fe73:e98f', 9501, "hello world");

public boolean Swoole\Server::sendwait ( integer $fd , string $data )

Alias: swoole_server->sendwait( integer $fd , string $data )

Send data to the remote socket in the blocking way.

Only available in SWOOLE_BASE mode.

Parameter

  • $fd the id number of client
  • $send_data the data to send

Return

The result of sending data

Example

public ReturnType Swoole\Server::set ( array $settings )

Alias: swoole_server->set( array $settings )

Set the runtime settings of the swoole server. The settings can be accessed by $server->setting when the swoole server has started.

Parameter

  • $setting the array of runtime settings

Setting example:

  • timeout => 2.5: select and epoll_wait timeout
  • poll_thread_num => 2: eactor thread num
  • max_conn => 10000: the max tcp connection number of the server
  • daemonize => 1: enable the daemon mode the server process
  • reactor_num => 2: set the number of system poll threads, the default setting is the number of CPU cores
  • worker_num => 4: set the number of worker processes
  • max_request => 2000: the number of requests processed by the worker process before been recycled
  • backlog => 128: TCP backlog number, the max number of connections waiting for acception
  • open_cpu_affinity => 1: enable CPU affinity
  • open_tcp_nodelay => 1: enable TCP_NoDelay
  • tcp_defer_accept => 5: delay a period of time for the new connection before been accepted
  • log_file => '/data/log/swoole.log': set the error logs location of the server
  • open_eof_check => true: enable buffer for the data receiving
  • package_eof => "\r\n\r\n": set EOF of the packages
  • heartbeat_check_interval => 30: set the interval of health checking for the TCP connections
  • heartbeat_idle_time => 60: set the max idle time before the idel connection been closed
  • dispatch_mode = 1: dispatch mode for child processes:
    • 1: round robin assignment
    • 2: assignment by mod
    • 3: preemptive assignment

Return

void

Example

<?php
$server->set(array(
    'reactor_num' => 2, //reactor thread num
    'worker_num' => 4,    //worker process num
    'backlog' => 128,   //listen backlog
    'max_request' => 50,
    'dispatch_mode' => 1,
));

public void Swoole\Server::shutdown ( void )

Alias: swoole_server->shutdown()

Shutdown the master server process, this function can be called in worker processes.

Shutdown server by system signal SIGTERM

kill -15 MASTER_PID

Parameter

void

Return

void

Example

public void Swoole\Server::start ( void )

Alias: swoole_server->start()

Start the swoole server, it will create worker_num + 2 processes by default:

  • main process: running multiple threads reactor, receive new connections and assign connections to worker processes
  • manager process: managing the worker processes
  • worker_num * child processes: process the data and business logics

Parameter

void

Return

The result if the swoole server starts successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    $server->send($fd, "Echo to #{$fd}: \n".$data);
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public array Swoole\Server::stats ( void )

Alias: swoole_server->stats()

Get the TCP connections stats of the current server.

Parameter

void

Return

The array of connections stats of the current server

<?php
array (
  'start_time' => 1409831644,  // the time of server since start
  'connection_num' => 1,       // the number of current connections 
  'accept_count' => 1,         // the number of connections accepted
  'close_count' => 0,          // the number of connections closed
  'tasking_num' => 1,          // the number of task which is queuing up
  'request_count' => 11,       // the number of request received
  'worker_request_count'       // the number of request received by the current worker
  'task_queue_num' => 10,      // the number of task which is in queue of task
  'task_queue_bytes' => 65536, // the number of bytes which is the space occupied by the queue of task
);

Example

public boolean Swoole\Server::stop ([ integer $worker_id ] )

Alias: swoole_server->stop([ integer $worker_id ] )

Stop current worker process or worker process by ID, this will emit 'WorkerStop' event and trigger the WorkerStop callback function.

  • Use the method to replace the function exit/die to end the worker process

Parameter

  • $worker_id : the id of worker process

Return

The result if the swoole server starts successfully

Example

<?php
$server = new swoole_server("127.0.0.1", 9501);
$server->on('connect', function ($server, $fd){
    echo "New connection established: #{$fd}.\n";
});
$server->on('receive', function ($server, $fd, $from_id, $data) {
    if(trim($data) == "stop")
    {
        $server->stop();
    }
    else
    {
        $server->send($fd, "Echo to #{$fd}: \n".$data);
        $server->close($fd);
    }
});

$server->on('WorkerStop', function($server, $worker_id){
    echo $worker_id . " stop\n";
});

$server->on('close', function ($server, $fd) {
    echo "Connection closed: #{$fd}.\n";
});
$server->start();

public mixed Swoole\Server::task ( string $data [, integer $dst_worker_id [, callable $callback ]] )

Alias: swoole_server->task( string $data [, integer $dst_worker_id [, callable $callback ]] )

Send data to the task worker processes.

To call this method, it needs to set the configuration of task_worker_num and the callback function of onTask and onFinish This method is non-blocking and return immediately after sending the task data to the pool of task worker.

Parameter

  • $data the data which is to send to the task worker, its type could any type except fot resource
  • $dst_worker_id the id number of task worker. If this parameter hasn't been passed, the swoole server would select a random and unoccupied task worker process.
  • $callback the callback function be called when the task has been finished. If this parameter has been passed, there is no need to register the callback function of the event of onFinish

Return

If the call of this method succeeds, the return is the task id which identifies the task If the call of this method fails, the return is false

Example

<?php
$task_id = $server->task("some data");

$server->task("taskcallback", -1, function (swoole_server $serv, $task_id, $data) {
    echo "Task Callback: ";
    var_dump($task_id, $data);
});

public void Swoole\Server::taskwait ( string $data [, float $timeout [, integer $worker_id ]] )

Alias: swoole_server->taskwait( string $data [, float $timeout [, integer $worker_id ]] )

The swoole_server->taskwait is similar to swoole_server->task. The two methods both send task data to the task worker pool to execute, but the former is blocking.

Parameter

  • $task_data the data which is to send to the task worker, its type could any type except fot resource
  • $timeout the time of timeout
  • $dst_worker_id the id number of task worker. If this parameter hasn't been passed, the swoole server would select a random and unoccupied task worker process.

Return

If the call of this method succeeds, the return is the result of task If the execution of this method exceeds the time of timeout, the return is false

Example

public void Swoole\Server::taskWaitMulti ( array $tasks [, double $timeout_ms ] )

Alias: swoole_server->taskWaitMulti( array $tasks [, double $timeout_ms ] )

Execute multiple tasks concurrently

Parameter

  • $tasks the array of task data which is to send to the task worker, its type could any type except fot resource
  • $timeout the time of timeout

Return

If the call of this method succeeds, the return is the array of the result of tasks If the execution of some task exceeds the time of timeout, its result will not be in the return array

Example

<?php
$tasks[] = mt_rand(1000, 9999); 
$tasks[] = mt_rand(1000, 9999); 
$tasks[] = mt_rand(1000, 9999); 
var_dump($tasks);

$results = $serv->taskWaitMulti($tasks, 10.0);

if (!isset($results[0])) {
    echo "Task 1: timeout.\n";
}
if (isset($results[1])) {
    echo "Task 2: {$results[1]}\n";
}
if (isset($results[2])) {
    echo "Task 3: {$results[2]}\n";
}

public void Swoole\Server::tick ( integer $interval_ms , callable $callback )

Alias: swoole_server->tick( integer $interval_ms , callable $callback )

Trigger a timer tick by interval. Alias of function swoole_timer_tick(). You can remove the timer later by calling swoole_timer_clear

Parameter

  • $time the number of millisecond
  • $callable the function that triggered repeatedly with a fixed time delay between each call

Return

The timer id which uniquely identifies the timer

Example

Use the swoole_server->tick in onReceive

<?php
function onReceive($server, $fd, $from_id, $data) {
    $server->tick(1000, function() use ($server, $fd) {
        $server->send($fd, "hello world");
    });
}

Use the swoole_server->tick in onWorkerStart

<?php
function onWorkerStart(swoole_server $serv, $worker_id)
{
    if (!$serv->taskworker) {
        $serv->tick(1000, function ($id) {
            var_dump($id);
        });
    } else {
        $serv->addtimer(1000);
    }
}