surva network: development blog

Articles and news about Minecraft: Bedrock Edition / PocketMine server development


Creating repeating / delayed tasks in PocketMine-MP

A common tool you frequently need when programming with the PocketMine-MP API are tasks. Using tasks, you’re able to repeat running code e. g. each 30 seconds, or to run delayed code for e. g. after 10 seconds.

Before we’re beginning creating our first task, it’s important to understand how PocketMine’s timing system works. We specify time in ticks, not in seconds. Conversion is easy, ticks = seconds * 20, so 3 seconds are 60 ticks.

Our first task

As an example, we’re going to create a task which broadcasts “Hello and welcome on my server!” each 30 seconds to all players on the server.

Let’s create a new class BroadcastHelloTask.php and extend the Task-class.

<?php
/**
 * ExamplePlugin | hello broadcasting task
 */

namespace surva\exampleplugin\task;

use pocketmine\scheduler\Task;

class BroadcastHelloTask extends Task {

}

Smart IDE’s already indicate that we’re missing the implementation of some methods, so we’re going to add them now.

/**
 * Broadcast message to players on task run
 *
 * @param int $currentTick
 */
public function onRun(int $currentTick): void {
    // TODO: Implement onRun() method.
}

The onRun method is called when the task is executed, e. g. after the 30 seconds are over. So we’re going to add our code we want to execute to this method.

In order to get all players on the server, access to the plugin’s main class is needed, so it’s time to add a variable containing it to our task class.

/* @var ExamplePlugin */
private $examplePlugin;

public function __construct(ExamplePlugin $exmpPl) {
    $this->examplePlugin = $exmpPl;
}

Now, we’re able to access our plugin’s main class, so let’s implement the onRun method:

/**
 * Broadcast message to players on task run
 *
 * @param int $currentTick
 */
public function onRun(int $currentTick): void {
    $plsOnServer = $this->examplePlugin->getServer()->getOnlinePlayers();

    foreach($plsOnServer as $player) {
        $player->sendMessage("Hello and welcome on my server!");
    }
}

Scheduling the task

Our task is ready now, we just need to schedule it.

To continue our example, we’re going the set the task to repeat each 30 seconds:

public function onEnable(): void {
    $this->getScheduler()->scheduleRepeatingTask(new BroadcastHelloTask($this), 600);
}

When the plugin gets enabled, our task gets immediately executed, after 30 seconds again, and again.

I’ve used $this as an argument for BroadcastHelloTask’s constructor (see BroadcastHelloTask class) and 600 as the period argument as 30 seconds * 20 ticks are 600.

Of course, there are also other ways of scheduling our task, e. g. we could execute it only once, but with 10 seconds delay:

$this->getScheduler()->scheduleDelayedTask(new BroadcastHelloTask($this), 200);