Java Reference
In-Depth Information
❷
public class
ExampleTask
extends
ServerTask {
private final
EZPlugin plugin;
❸
public
ExampleTask(EZPlugin plugin) {
super(Canary.getServer(), 0, true);
// delay, isContinuous
this.plugin = plugin;
// you can keep a reference to your plugin as I've done here,
// or to any other variable you pass in
}
public void
run() {
// Do something interesting...
Canary.instance().getServer().broadcastMessage(
"Surprise!"
);
}
}
In this case, you'd put this code in its own file, which must be named
Example-
Task.java
(to match the name on the line at
❷
), and be in a directory named
after the package (to match the name at
❶
).
So far so good, but what's up with this interesting-looking function that has
no return type and is named
ExampleTask
—the exact same name as our class?
Remember, that's called a
constructor
. That's the function Java calls when
it's creating a new
ExampleTask
.
So to create our
ExampleTask
, you have to pass in a
EZPlugin
to the
new
(which
gets passed to your constructor). In other words, you have to give it your main
plugin object. That way this task can get at all the server things it might need
to, like the world, players, and so on. That's not mandatory, but it can be
useful.
Now that you have a task that will do something interesting (well, sort of),
how do you schedule it?
Schedule to Run Later
Now back to your main plugin: once you have the task defined over in its own
class, you can create an object of that class from your main plugin using
new
,
and schedule it to be run in the future using
addSynchronousTask()
.
ExampleTask task =
new
ExampleTask(plugin);
Canary.getServer().addSynchronousTask(task);
plugin
should be a variable that's set to your main plugin. If you're putting this
code in a non-static function in your plugin, you can use the Java keyword
this
, which means “this plugin object.” If you're putting this code in a static
function, you need a static variable (like
plugin
) that has previously been set