I need to run one of my functions in the background because it brings to much lagg to my server. I found this: http://php.net/manual/de/gearmanclient.addtaskbackground.php But I don't know how to set it for one function
Not sure if gearman will work for pocketmine. Show us the function. If you are directly changing variables in the main thread it will cause issues.
I run a command (/info). This will start the function getInfo. PHP: public function getInfo(/*some variables*/) {//$info = from websitereturn $info;}
PHP: public function getInfo($ip, $port, $timeout = 10) {if ($ip and $port and $timeout){ $minecraft = @fsockopen("$ip", $port, $timeout);}if($minecraft){$status = "online";} else {$status = "offline";}}
Create a class "InfoTask" and extend it with \pocketmine\scheduler\AsyncTask. Create a public function "onRun()" in the class. PHP: private $ip, $port, $timeout;public function __construct($ip, $port, $timeout = 10){ $this->ip = $ip; $this->port = $port; $this->timeout = $timeout;}public function onRun(){ $minecraft = @fsockopen($this->ip, $this->port, $this->timeout); $status = $minecraft ? "online" : "offline"; $this->setResult($status);}public function onCompletion(Server $server){ $server->getLogger()->notice(" Background task has finished. The output was: ".$this->getResult());} Call InfoTask from another class: PHP: //$ip = ...//$port = ...//$timeout = 10Server::getInstance()->getScheduler()->scheduleAsyncTask(new InfoTask($ip, $port, $timeout)); You can refer to the docs for function descriptions.
And how can I get the result? "Server::getInstance()->getScheduler()->scheduleAsyncTask(new InfoTask($ip, $port, $timeout));" only starts it
It's terrible idea to pass objects from main thread to another. You want to send this data to player that issued the command, right? So pass player name to AsyncTask and do this PHP: onCompletation(Server $server) { if(($player = $server->getPlayer($this->issuer)) { $player->sendMessage($this->getResult()); }}
No. I have another function in my main thread where I start the task. There I want to return the status
I tried to get the result in another file. But it gives me an error PHP: $status = $this->getServer()->getScheduler()->scheduleAsyncTask(new StatusTask($ip, $port, $timeout));return $status->getResult();//error: Call to a member function getResult() on null
PHP: private $ip, $port, $timeout, $server, $status;public function __construct(Server $server, $ip, $port, $timeout = 10){ $this->ip = $ip; $this->port = $port; $this->timeout = $timeout; $this->server = $server;}public function onRun(){ $minecraft = @fsockopen($this->ip, $this->port, $this->timeout); $this->status = $minecraft == true ? "online" : "offline";}public function onCompletion(Server $server){ $server->getLogger()->notice(" Background task has finished. The output was: ".$this->status); $server->getPluginManager()->getPlugin->("pluginName")->result = $this->status;}