How to make a function be called every 2 ticks

Henry picture Henry · Apr 21, 2013 · Viewed 11.1k times · Source

I'm making a bukkit plugin for my friend, and I want to find out how to call a function every 2 ticks (1/10th of a second).

Answer

Tips48 picture Tips48 · Apr 21, 2013

Well, this probably isn't where you want to look. You should be using this for any of your development needs.
Either way, I can answer your question. You want to use the built in scheduler. You can access it using

server.getScheduler();

Specifically, your going to want to create a Runnable and make it call your method every 2 ticks.

int id = server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
    public void run() {
        myMethod();
    }}, 0, 2);

I'll explain the difference with sync and async in a second, but this should accomplish what you want. The first argument is just a reference to the plugin (Normally this or plugin). The second is the runnable, and you should obviously replace myMethod with the method you want to call. The third argument is the amount of delay (In ticks) until the method first runs. I assumed 0, but it might also be two depending on what you want to do. The last argument is the amount of time between runs, which you wanted to be two.
You'll notice that the method returns an integer, which you can use to cancel the task like so:

server.getScheduler().cancelTask(id);

It's important to discuss the difference between Async and Sync. You'll notice the method we called in the beginning says scheduleSyncRepeatingTask. Sync means that the Runnable which we specified as the second argument will be run on the main thread of the server. ANY method that calls a Bukkit/CraftBukkit/Minecraft method MUST be run as sync. If you run something that say, modifies a block, as Async you could completely corrupt the server. Just don't do it ;) Async, on the other hand, creates a seperate thread for the Runnable, is used for background tasks, such as copying and pasting a file or checking what time it is. Once again, NEVER run a method that will modify the world as Async.

Lastly, in the future if you only wanted to run a method once and then not have it repeat, you can just use the method int id = scheduleSyncDelayedTask(plugin, Runnable, 2), with the first two arguments being the same and the third being the delay until the runnable is run (Ticks)

Good luck,
Tips