1. Go to this page and download the library: Download functions/think-swoole 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/ */
/**
* Created by PhpStorm.
* User: xavier
* Date: 2018/8/19
* Time: 下午8:28
*/
namespace app\lib;
use think\swoole\template\Task;
class TestTask extends Task
{
public function _initialize(...$arg)
{
// TODO: Implement _initialize() method.
}
public function run($serv, $task_id, $fromWorkerId)
{
// TODO: Implement run() method.
}
}
namespace app\index\controller;
use think\swoole\facade\Task;
class Index
{
public function hello()
{
//投递任务模板
$task=new \app\lib\TestTask();
Task::async($task);
//异步任务投递闭包
Task::async(function ($serv, $task_id, $data) {
$i = 0;
while ($i < 10) {
$i++;
echo $i;
sleep(1);
}
});
return 'hello' ;
}
}
namespace app\lib;
/**
* Created by PhpStorm.
* User: xavier
* Date: 2018/8/19
* Time: 下午8:01
*/
use think\swoole\template\Timer;
class TestTimer extends Timer
{
public function _initialize(...$arg)
{
// TODO: Implement _initialize() method.
}
public function run()
{
$i=0;
// TODO: Implement run() method.
while($i<10){
var_dump(12);
$i++;
sleep(1);
}
}
}
namespace app\index\controller;
use think\swoole\facade\Task;
use think\swoole\facade\Timer;
class Index
{
public function hello()
{
//闭包方式使用定时器
Timer::tick(1000,function(){
var_dump(1);
});
//使用定时器模板
$t=new \app\lib\TestTimer();
Timer::tick(1000,$t);
return 'hello,' ;
}
}
namespace app\index\controller;
use think\Container;
class Index
{
public function hello()
{
$swoole=Container::get('swoole');//获取swoole实例
}
}
'wokerstart'=>function($server, $worker_id){
//如果只在一个进程处理 则可以这样
if (0==$worker_id){
//这样只会在第一个woker进程处理
}
}
/**
* Created by PhpStorm.
* User: xavier
* Date: 2018/8/23
* Time: 下午5:27
* Email:[email protected]
*/
namespace app\lib;
use think\swoole\template\WorkerStart as Woker;
class WorkStart extends Woker
{
public function _initialize($server, $worker_id)
{
// TODO: Implement _initialize() method.
}
public function run()
{
var_dump(1);
}
}