PHP code example of jingwu / phpbeanstalk
1. Go to this page and download the library: Download jingwu/phpbeanstalk 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/ */
jingwu / phpbeanstalk example snippets
ingwu\PhpBeanstalk\Client;
$cfg = [
'persistent' => true,
'host' => '127.0.0.1',
'port' => 11300,
'timeout' => 1, //连接超时设置
'stream_timeout' => 1, //数据流超时设置
'force_reserve_timeout' => 1, //强制 reserve 设置超时,默认1秒
];
$client = new Client($cfg);
$tube = 'flux';
//队列生产者示例
$client->connect();
$client->useTube($tube);
$client->put(
23, // 设置任务优先级23Give the job a priority of 23.
0, // 不等待,直接发送任务到ready队列
60, // 设置任务1分钟的执行时间
'/path/to/cat-image.png' // 任务的内容
);
$client->disconnect();
//队列消费者示例
$client = new Client();
$client->connect();
$client->watch($tube);
while(true) {
$job = $client->reserve(); // 阻塞,直到有可用的任务
// 网络原因,会导致取不到可用的任务,而返回false
// 极个别情况下会形成死循环
if($job === false) {
sleep(1);
continue;
}
// $job 实例如下:
// array('id' => 123, 'body' => '/path/to/cat-image.png')
// 设置任务执行中
$result = touch($job['body']);
if($result) {
$client->delete($job['id']);
} else {
$client->bury($job['id']);
}
}
// 断开连接
// $client->disconnect();