Skip to content
enebo edited this page Dec 11, 2011 · 1 revision

In Purugin (and in Bukkit) you are strongly recommended to not use Threads, but instead submit runnable tasks. The primary reason for this is Bukkit is generally not thread-safe. The second and almost equally important reason is that if you disable your Plugin you might want your background processing to actually stop.

There are two types of tasks: synchronous (sync) and asynchronous (asynch). Since most methods in Bukkit are not thread-safe you must call those methods in a sync task. A sync task actually gets executed on the main game thread. This also means you must use extreme caution when writing sync tasks, because one which lasts too long will end up causing the game to pause (appear to be lagged).

When you know you are hitting only thread-safe Bukkit API methods or you are just doing your own thing outside of the Bukkit APIs then you can submit asynchronous tasks. These will run in parallel in a separate thread.

To use tasks you just need to include the Purugin::Tasks module to your Purugin:

    class MyPurugin
      include Purugin::Plugin, Purugin::Tasks

      def on_enable
        sync_task(0, 3) { update_cache }
      end
    end

The Purugin::Tasks module exposed two methods to you: sync_task, async_task. Both methods have two optional parameters: delay and period. delay represents how long since issuing the task (in seconds) it should wait before executing. Providing no delay will mean execute as soon as possible. If period is provided, then this represents a task which should repeat every period seconds.