In this post we’ll use the Bukkit Scheduler to decrease the likelihood of our Minecraft client being dropped while performing computationally intensive tasks in our ScriptCraft code–tasks like building gigantic structures. As an added bonus we also get to watch our huge structures being built (rather than just poofing into existence as they currently do). Poof!
From what I can gather ScriptCraft currently performs all of its work in the main server thread. The main thread also takes care of a number of important tasks including the networking logic which manages the connection to your Minecraft client. Now, running on the main thread isn’t a problem in itself, it only becomes a problem once you start doing some heavy lifting like rendering a 500 x 100 x 500 rectangular prism (at least for my little server):
If your ScriptCraft code is gobbling up too much time you’ll end up seeing this screen:
I see it frequently.
One way to decrease your chances of seeing the old dirt screen is to punt off your ScriptCraft tasks off into another thread thereby giving the main server thread a little breathing room. Here’s an example of using the schedule to draw a large rectangular prism:
As you can see it is only a few extra lines of code and doesn’t add too much complexity. We get a reference to the scheduler and call the scheduleAsyncDelayedTask method supplying a reference to the ScriptCraft plugin and the task we wish to run.
Now a async delayed task isn’t the only type we can use in our ScriptCraft–in fact sometimes we shouldn’t use it. All in all Bukkit allows us to schedule four different types of tasks:
- Synchronous Delayed – Schedules a one-time task to run in the main thread with an optional delay.
- Synchronous Repeating – Schedules a repeating task to run in the main thread on a specified period with an optional delay.
- Asynchronous Delayed – Schedules a one-time task to run in a separate thread managed by the scheduler with an optional delay.
- Asynchronous Repeating – Schedules a repeating task to run in a separate thread managed by the scheduler with an optional delay.
Finally, remember this is no silver bullet! If your doing too much work and your server can’t keep up nothing will save you from being dropped.