Skip to content

ScheduleHandler

S'pugn edited this page Nov 11, 2021 · 1 revision

Notes

Scripts are called in different threads, meaning some actions like placing blocks, giving items, or teleporting players in game can not be done through scripts normally. This snippet of code, which I like to call "ScheduleHandler", uses BukkitScheduler to "link" back into the main server thread to perform actions that do require it.

Script

/**
 * NONE type script
 *
 * ScheduleHandler IS TO MANAGE TASKS THAT CAN'T BE RUN
 * ASYNCHRONOUSLY (giving potion effects, placing blocks,
 * spawning entities, etc).
 *
 * TO IMPORT:
 *   const ScheduleHandler = load(`ScheduleHandler.js`);
 *
 * @author      Expugn
 * @version     0.1
 * @type        NONE
 */
function main() {
    return function (callback, delay = 0) {
        const Bukkit = Java.type("org.bukkit.Bukkit");
        const Runnable = Java.type("java.lang.Runnable");
        const task = Java.extend(Runnable, {
            run: callback
        });

        const scheduler = Bukkit.getScheduler();
        scheduler.runTaskLater(sm.getPlugin(), new task(), delay);
    }
}
main();

Example Usage

function main() {
    const ScheduleHandler = load("ScheduleHandler.js");
    ScheduleHandler(() => {
        print("Hello, from the main thread!");
    });
}
function main() {
    const ScheduleHandler = load("ScheduleHandler.js");
    ScheduleHandler(hello);
    function hello() {
        print("Hello, from the main thread!");
    }
}
Clone this wiki locally