Skip to main content

Task Scheduling

  • Related classes: TaskBuilder, TimeUnit, KapiTask

Build and run a task

TaskBuilder.create(() -> {
// Your code
}).schedule();

This will execute your code on the next server tick (1 tick = 0.05s).

tip

you can keep the TaskBuilder instance, and call schedule() on it as many times as you want. You can even modify it in-between calls!

Task Modifiers

You can call methods on the TaskBuilder instance to modify when or how many times the task will be executed.

To run a task after some delay:

int delayInTicks = 30; // 1.5 seconds
TaskBuilder.create(() -> {
// This will run once after 1.5 seconds
}).delay(delayInTicks).schedule();

Alternatively, you can specify a TimeUnit:

int delayInHours = 2; // 2 hours
TaskBuilder.create(() -> {
// This will run once after 2 hours
}).delay(delayInHours, TimeUnit.HOURS).schedule();

Stopping Conditions

So far, we've seen interval tasks run forever. However, you may add one or more stopping conditions to stop a task's execution.

You can specify how many times you want a task to repeat:

TaskBuilder.create(() -> {
// Will run every 5 seconds, for 20 times, and then stop
}).interval(5, TimeUnit.SECONDS).repeat(20).schedule();
warning

Calling schedule() on a task with a stopping condition and without an interval will automatically set the interval to 1 tick (will run 20 times per seconds)

info

You may use multiple stopping conditions together.
The task will stop whenever the first stopping condition is reached.

Task Completion Callback

To run some code when a task finishes, you can do:

TaskBuilder.create(() -> {
System.out.println("Task Started");
}).onFinish(() -> {
System.out.println("Task Finished");
}).schedule();

This may be very useful, especially when having multiple stop conditions.

Task State Management

The KapiTask interface holds useful information such as:

  • Task ID - the ID is needed to identify the task in certain Spigot methods.
  • Owner - the plugin that scheduled the task.
  • Sync - Wether the task is synchronous or asynchronous.
  • Cancelled - Wether the task has been cancelled already.
  • Delay - the initial delay the task was created with.
  • Interval - the initial interval the task was created with.
  • Times Ran - the amount of times the task has run.
  • Duration - the duration (in ticks, excluding delay) the task has been running for.

Manually cancelling a Task

It can also be used to cancel a task manually:

TaskBuilder.create((task) -> {
boolean someLogic = true;
if (someLogic && task.getTimesRan() > 2) {
task.cancel();
}
}).interval(20, TimeUnit.SECONDS).schedule();

Methods that optionally accept a KapiTask

  • create(task -> { /* task code */ })
  • whileCondition(task -> { /* condition */ })
  • onFinish(task -> { /* on finish code */ })
  • schedule(task -> { /* task code */ })