BukkitWiki

Welcome to the BukkitWiki!

This Wiki is home to Bukkit's documentation and regulations surrounding the Bukkit Project and it's services. Want to help out? We would love to have you! Signup to get started!

READ MORE

BukkitWiki
No edit summary
Tag: Visual edit
No edit summary
Tag: Visual edit: Switched
 
Line 1: Line 1:
  +
This tutorial will guide you in using the scheduler provided by bukkit. It will allow you to defer the execution of code to a later time. This is not the same as registering a [http://jd.bukkit.org/org/bukkit/event/Listener.html Listener], a block of code which is executed in response to an [http://wiki.bukkit.org/Event_API_Reference event] in the game. Blocks of code may also be scheduled to be executed repeatedly at a fixed interval, with or without a delay. They will continue to execute until completed, or canceled, or your plugin is disabled.
   
  +
When using [[#BukkitRunnable|BukkitRunnable]], with a separate class, scheduling work occurs in two steps for the programmer.
Este tutorial vai ajudar você a usar scheduler do bukkit. Ele irá premitir que você defina a execução do código com um certo delay. Isto não é o mesmo que registar um [http://jd.bukkit.org/apidocs/index.html?org/bukkit/event/Listener.html Listener], um bloco de código que irá responder a um [http://wiki.bukkit.org/Event_API_Reference evento] no jogo. Blocos de código também podem ser "schedulados" para serem executados repetidamente num itervalo fixo, com ou sem delay. Eles continuaram a ser executados ate serem completos, cancelados, ou o seu plugin ser desativado.
 
  +
# Define the work to be done, see the section [[#Defining_work|Defining Work]]
  +
# Notify Bukkit when the work should be executed, see the section [[#Scheduling_Work|Scheduling Work]]
   
  +
Alternatively, work can be scheduled directly with the scheduler, this also occurs in two steps for the programmer.
Usando [[Scheduler Programming#BukkitRunnable|BukkitRunnable]], em uma classe separado, scheduling funciona em dois passos para o programador..
 
  +
# Define the work to be done, in a Runnable or Callable
# Defenir o trabalho para estar completo, veja a secção em [[Scheduler Programming#Defining work|Defining Work]]
 
  +
# Then directly scheduling the work with the Bukkit Scheduler, see the section [[#BukkitScheduler|BukkitScheduler]]
# Notificar o Bukkit quando o trabalho deve ser executado, veja a secção em [[Scheduler Programming#Scheduling Work|Scheduling Work]]
 
Alternativamente, o trabalho pode ser scheduled diretamente com o scheduler, isto também ocorre em dois passos para o programador.
 
# Defenir o trabalho a ser feito, em um Runablle ou Callable
 
# sheduling diretamente com o Bukkit sheduler, veja a secção [[Scheduler Programming#BukkitScheduler|BukkitScheduler]]
 
   
 
= BukkitRunnable =
 
= BukkitRunnable =
[http://jd.bukkit.org/apidocs/index.html?org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable] é uma implementação abstrata [http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/Runnable.html Runnable]. It also supports additional operations that a Runnable is not capable of, most conveniently, BukkitRunnables can schedule and cancel their own execution. However, if the BukkitRunnable did not schedule itself for execution, it cannot cancel itself from execution. BukkitRunnables are not schedulers, do not contain any scheduler logic, and are not expensive to create. Plugins should prefer defining a BukkitRunnable and calling the appropriate run method over directly scheduling a Runnable with the BukkitScheduler.
+
[http://jd.bukkit.org/org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable] is an abstract implementation of [http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/Runnable.html Runnable]. It also supports additional operations that a Runnable is not capable of, most conveniently, BukkitRunnables can schedule and cancel their own execution. However, if the BukkitRunnable did not schedule itself for execution, it cannot cancel itself from execution. BukkitRunnables are not schedulers, do not contain any scheduler logic, and are not expensive to create. Plugins should prefer defining a BukkitRunnable and calling the appropriate run method over directly scheduling a Runnable with the BukkitScheduler.
   
: ''For more information on BukkitRunnable, see the [http://jd.bukkit.org/apidocs/index.html?org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable JavaDocs]''
+
: ''For more information on BukkitRunnable, see the [http://jd.bukkit.org/org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable JavaDocs]''
   
 
== Defining work ==
 
== Defining work ==
Plugins should first [http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html extend] [http://jd.bukkit.org/apidocs/index.html?org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable] to define work that needs to be done. In other words, the definition of the run method is what you want executed in accordance to a schedule.
+
Plugins should first [http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html extend] [http://jd.bukkit.org/org/bukkit/scheduler/BukkitRunnable.html BukkitRunnable] to define work that needs to be done. In other words, the definition of the run method is what you want executed in accordance to a schedule.
   
 
=== Basic Example ===
 
=== Basic Example ===
Line 27: Line 27:
 
private final JavaPlugin plugin;
 
private final JavaPlugin plugin;
   
public void ExampleTask(JavaPlugin plugin) {
+
public ExampleTask(JavaPlugin plugin) {
 
this.plugin = plugin;
 
this.plugin = plugin;
 
}
 
}
Line 73: Line 73:
   
 
== Scheduling Work ==
 
== Scheduling Work ==
After defining the task, the plugin needs to schedule the task. BukkitRunnables are scheduled when the desired run method is invoked on an instance of the task. The list of methods for BukkitRunnable can be found in the [http://jd.bukkit.org/rb/apidocs/index.html?org/bukkit/scheduler/BukkitRunnable.html Javadocs for BukkitRunnable]. The different run methods all return a [[#BukkitTask | BukkitTask]] object
+
After defining the task, the plugin needs to schedule the task. BukkitRunnables are scheduled when the desired run method is invoked on an instance of the task. The list of methods for BukkitRunnable can be found in the [http://jd.bukkit.org/org/bukkit/scheduler/BukkitRunnable.html Javadocs for BukkitRunnable]. The different run methods all return a [[#BukkitTask | BukkitTask]] object
   
 
{{warning| Asynchronous tasks should never access any API in Bukkit}}
 
{{warning| Asynchronous tasks should never access any API in Bukkit}}
Line 100: Line 100:
 
public ExampleListener(ExamplePlugin plugin) {
 
public ExampleListener(ExamplePlugin plugin) {
 
this.plugin = plugin;
 
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
+
this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
 
}
 
}
   
Line 113: Line 113:
   
 
=== Self-Canceling Example ===
 
=== Self-Canceling Example ===
This is example takes the above ExampleSelfCancelingTask and scheules it to run every 20 ticks after waiting 10 ticks.
+
This is example takes the above ExampleSelfCancelingTask and schedules it to run every 20 ticks after waiting 10 ticks.
 
<blockquote><source lang="java">import org.bukkit.event.EventHandler;
 
<blockquote><source lang="java">import org.bukkit.event.EventHandler;
 
import org.bukkit.event.Listener;
 
import org.bukkit.event.Listener;
Line 135: Line 135:
 
public ExampleListener(ExamplePlugin plugin) {
 
public ExampleListener(ExamplePlugin plugin) {
 
this.plugin = plugin;
 
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
+
this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
 
}
 
}
   
Line 170: Line 170:
 
public ExampleListener(ExamplePlugin plugin) {
 
public ExampleListener(ExamplePlugin plugin) {
 
this.plugin = plugin;
 
this.plugin = plugin;
plugin.getServer().getPluginManager().registerEvents(this, plugin);
+
this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
 
}
 
}
 
 
Line 191: Line 191:
   
 
= BukkitScheduler =
 
= BukkitScheduler =
The [http://jd.bukkit.org/rb/apidocs/index.html?org/bukkit/scheduler/BukkitScheduler.html BukkitScheduler] allows plugins to schedule a [http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/Runnable.html Runnable] and/or a [http://docs.oracle.com/javase/6/docs/api/index.html?java/util/concurrent/Callable.html Callable] , for execution at a later time. The list of methods for BukkitScheduler can be found in the [http://jd.bukkit.org/rb/apidocs/index.html?org/bukkit/scheduler/BukkitScheduler.html Javadocs for BukkitScheduler].
+
The [http://jd.bukkit.org/org/bukkit/scheduler/BukkitScheduler.html BukkitScheduler] allows plugins to schedule a [http://docs.oracle.com/javase/6/docs/api/index.html?java/lang/Runnable.html Runnable] and/or a [http://docs.oracle.com/javase/6/docs/api/index.html?java/util/concurrent/Callable.html Callable] , for execution at a later time. The list of methods for BukkitScheduler can be found in the [http://jd.bukkit.org/org/bukkit/scheduler/BukkitScheduler.html Javadocs for BukkitScheduler].
   
 
{{Note|Plugins should not schedule a BukkitRunnable with the scheduler, instead they should run the BukkitRunnable with the desired schedule.}}
 
{{Note|Plugins should not schedule a BukkitRunnable with the scheduler, instead they should run the BukkitRunnable with the desired schedule.}}
Line 204: Line 204:
 
public final class ExamplePlugin extends JavaPlugin {
 
public final class ExamplePlugin extends JavaPlugin {
 
public void onEnable() {
 
public void onEnable() {
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
+
BukkitScheduler scheduler = getServer().getScheduler();
 
scheduler.scheduleSyncDelayedTask(this, new Runnable() {
 
scheduler.scheduleSyncDelayedTask(this, new Runnable() {
 
@Override
 
@Override
Line 224: Line 224:
 
public final class ExamplePlugin extends JavaPlugin {
 
public final class ExamplePlugin extends JavaPlugin {
 
public void onEnable() {
 
public void onEnable() {
BukkitScheduler scheduler = Bukkit.getServer().getScheduler();
+
BukkitScheduler scheduler = getServer().getScheduler();
 
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
 
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
 
@Override
 
@Override
Line 238: Line 238:
   
 
== BukkitTask ==
 
== BukkitTask ==
A [http://jd.bukkit.org/rb/apidocs/index.html?org/bukkit/scheduler/BukkitTask.html BukkitTask] object is returned whenever a Runnable is scheduled. This object represents the task the scheduled task being executed by the scheduler. For more information see, [http://jd.bukkit.org/rb/apidocs/index.html?org/bukkit/scheduler/BukkitTask.html Javadocs for BukkitTask].
+
A [http://jd.bukkit.org/org/bukkit/scheduler/BukkitTask.html BukkitTask] object is returned whenever a Runnable is scheduled. This object represents the task the scheduled task being executed by the scheduler. For more information see, [http://jd.bukkit.org/org/bukkit/scheduler/BukkitTask.html Javadocs for BukkitTask].
   
 
== Callable and Future ==
 
== Callable and Future ==
Line 249: Line 249:
 
# An asynchronous task can schedule a synchronous task.
 
# An asynchronous task can schedule a synchronous task.
 
# A synchronous task can schedule an asynchronous task.
 
# A synchronous task can schedule an asynchronous task.
  +
# If you want to schedule something at a fixed time, by calculating how many ticks until that point in time, you should use an asynchronous task. If you don't, lag will increase the delay.
   
 
{{Languages|Scheduler Programming}}
 
{{Languages|Scheduler Programming}}

Latest revision as of 14:20, 9 November 2016

This tutorial will guide you in using the scheduler provided by bukkit. It will allow you to defer the execution of code to a later time. This is not the same as registering a Listener, a block of code which is executed in response to an event in the game. Blocks of code may also be scheduled to be executed repeatedly at a fixed interval, with or without a delay. They will continue to execute until completed, or canceled, or your plugin is disabled.

When using BukkitRunnable, with a separate class, scheduling work occurs in two steps for the programmer.

  1. Define the work to be done, see the section Defining Work
  2. Notify Bukkit when the work should be executed, see the section Scheduling Work

Alternatively, work can be scheduled directly with the scheduler, this also occurs in two steps for the programmer.

  1. Define the work to be done, in a Runnable or Callable
  2. Then directly scheduling the work with the Bukkit Scheduler, see the section BukkitScheduler

BukkitRunnable

BukkitRunnable is an abstract implementation of Runnable. It also supports additional operations that a Runnable is not capable of, most conveniently, BukkitRunnables can schedule and cancel their own execution. However, if the BukkitRunnable did not schedule itself for execution, it cannot cancel itself from execution. BukkitRunnables are not schedulers, do not contain any scheduler logic, and are not expensive to create. Plugins should prefer defining a BukkitRunnable and calling the appropriate run method over directly scheduling a Runnable with the BukkitScheduler.

For more information on BukkitRunnable, see the BukkitRunnable JavaDocs

Defining work

Plugins should first extend BukkitRunnable to define work that needs to be done. In other words, the definition of the run method is what you want executed in accordance to a schedule.

Basic Example

This is an example definition of a task that can be scheduled.

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

public class ExampleTask extends BukkitRunnable {

    private final JavaPlugin plugin;

    public ExampleTask(JavaPlugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public void run() {
        // What you want to schedule goes here
        plugin.getServer().broadcastMessage("Welcome to Bukkit! Remember to read the documentation!");
    }

}

Self-Canceling Example

This is an example of a definition of a task that will cancel itself when it has executed the specified number of times

import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

public class ExampleSelfCancelingTask extends BukkitRunnable {

    private final JavaPlugin plugin;
    
    private int counter;

    public ExampleSelfCancelingTask(JavaPlugin plugin, int counter) {
        this.plugin = plugin;
        if (counter < 1) {
            throw new IllegalArgumentException("counter must be greater than 1");
        } else {
            this.counter = counter;
        }
    }

    @Override
    public void run() {
        // What you want to schedule goes here
        if (counter > 0) { 
            plugin.getServer().broadcastMessage("Commence greeting in " + counter--);
        } else {
            plugin.getServer().broadcastMessage("Welcome to Bukkit! Remember to read the documentation!");
            this.cancel();
        }
    }

}

Scheduling Work

After defining the task, the plugin needs to schedule the task. BukkitRunnables are scheduled when the desired run method is invoked on an instance of the task. The list of methods for BukkitRunnable can be found in the Javadocs for BukkitRunnable. The different run methods all return a BukkitTask object

Warning Warning: Asynchronous tasks should never access any API in Bukkit

Example

This is an example of a plugin which registers a listener and when a player joins, schedules a task to be run 20 ticks later.

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

public final class ExamplePlugin extends JavaPlugin {

    @Override
    public void onEnable() {
        new ExampleListener(this);
    }
}

class ExampleListener implements Listener {

    private final ExamplePlugin plugin;

    public ExampleListener(ExamplePlugin plugin) {
        this.plugin = plugin;
        this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        // Create the task and schedule to run it once, after 20 ticks
        BukkitTask task = new ExampleTask(this.plugin).runTaskLater(this.plugin, 20);
    }

}

Self-Canceling Example

This is example takes the above ExampleSelfCancelingTask and schedules it to run every 20 ticks after waiting 10 ticks.

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

public final class ExamplePlugin extends JavaPlugin {

    @Override
    public void onEnable() {
        new ExampleListener(this);
    }
}

class ExampleListener implements Listener {

    private final ExamplePlugin plugin;

    public ExampleListener(ExamplePlugin plugin) {
        this.plugin = plugin;
        this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        // Create the task and schedule
        BukkitTask task = new ExampleSelfCancelingTask(this.plugin, 5).runTaskTimer(this.plugin, 10, 20);
    }

}

Anonymous BukkitRunnable Example

An anonymous BukkitRunnable will allow you to schedule a task, without creating a new class with a name. This examples combines the above two basic examples.

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

public final class ExamplePlugin extends JavaPlugin {
 
    @Override
    public void onEnable() {
        new ExampleListener(this);
    }
}
 
class ExampleListener implements Listener {
 
    private final ExamplePlugin plugin;
 
    public ExampleListener(ExamplePlugin plugin) {
        this.plugin = plugin;
        this.plugin.getServer().getPluginManager().registerEvents(this, plugin);
    }
 
    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        // Create the task anonymously and schedule to run it once, after 20 ticks
        new BukkitRunnable() {
        
            @Override
            public void run() {
                // What you want to schedule goes here
                plugin.getServer().broadcastMessage(
                    "Welcome to Bukkit! Remember to read the documentation!");
            }
            
        }.runTaskLater(this.plugin, 20);
    }
 
}

BukkitScheduler

The BukkitScheduler allows plugins to schedule a Runnable and/or a Callable , for execution at a later time. The list of methods for BukkitScheduler can be found in the Javadocs for BukkitScheduler.

Lightbulb Note: Plugins should not schedule a BukkitRunnable with the scheduler, instead they should run the BukkitRunnable with the desired schedule.

Example

Example for directly scheduling an anonymous Runnable with the BukkitScheduler to run after 20 ticks.

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;

public final class ExamplePlugin extends JavaPlugin {
    public void onEnable() {
        BukkitScheduler scheduler = getServer().getScheduler();
        scheduler.scheduleSyncDelayedTask(this, new Runnable() {
            @Override
            public void run() {
                // Do something
            }
        }, 20L);
    }
}

Repeating Example

Example for directly scheduling an anonymous Runnable with the BukkitScheduler to run every twenty ticks, forever, starting from when you schedule it.

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;

public final class ExamplePlugin extends JavaPlugin {
    public void onEnable() {
        BukkitScheduler scheduler = getServer().getScheduler();
        scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
            @Override
            public void run() {
                // Do something
            }
        }, 0L, 20L);
    }
}
Warning Warning: Asynchronous tasks should never access any API in Bukkit

BukkitTask

A BukkitTask object is returned whenever a Runnable is scheduled. This object represents the task the scheduled task being executed by the scheduler. For more information see, Javadocs for BukkitTask.

Callable and Future

A Callable given to the scheduler to call synchronously returns a Future. These are standard Java classes, for more information see, Javadocs for Callable and Javadocs for Future

Tips for thread safety

The Bukkit API, with the exception of the scheduler package, is not thread safe nor guaranteed to be thread safe.

  1. Asynchronous tasks should never access any API in Bukkit.
  2. Do not access or modify shared collections from your asynchronous tasks. Normal collections are not thread-safe. This also applies to objects which are not thread safe.
  3. An asynchronous task can schedule a synchronous task.
  4. A synchronous task can schedule an asynchronous task.
  5. If you want to schedule something at a fixed time, by calculating how many ticks until that point in time, you should use an asynchronous task. If you don't, lag will increase the delay.
Language   EnglishбеларускаяDeutschespañolsuomifrançaisitaliano한국어Nederlandsnorskpolskiportuguêsрусскийlietuviųčeština