Gathering plugin instance


I’m trying to create my first sponge plugin. I’ve encountered a problem that I can’t fully understand. I want to make async task, doing it just like in scheduler docs, but plugin refuses to work.
Here is my part of code I use to create task:

    private final Task.Builder taskBuilder = Sponge.getScheduler().createTaskBuilder();

    private Task makeTask() {
        return taskBuilder
                .execute(new ScheduledWeatherStateUpdateHandler(this))

My IDE tells me that Casting ‘this’ to ‘Plugin’ is redundant, but when I try to run plugin event with that cast, it fails with stacktrace

[14:32:21 ERROR] [Sponge]: Could not pass GameStartedServerEvent$Impl to Plugin{id=realweather, name=RH-RealWeather, version=1.1, authors=[Micha▒ "Bopke" Kubik], source=mods\RealWeather-1.1.jar}
java.lang.ClassCastException: ovh.rehost.realWeatherSponge.RealWeather cannot be cast to org.spongepowered.api.plugin.Plugin
        at ovh.rehost.realWeatherSponge.RealWeather.makeTask( ~[RealWeather.class:?]
        at ovh.rehost.realWeatherSponge.RealWeather.onServerStart( ~[RealWeather.class:?]
        at org.spongepowered.common.event.listener.GameStartedServerEventListener_RealWeather_onServerStart3.handle(Unknown Source) ~[?:?]

When I run the plugin without that cast, it crashes with stacktrace:

[14:50:14 ERROR] [Sponge]: The Scheduler tried to run the task RealWeatherChecker owned by Plugin{id=realweather, name=RH-RealWeather, version=1.1, authors=[Micha▒ "Bopke" Kubik], source=mods\RealWeather-1.1.jar}, but an error occured.
java.lang.IllegalArgumentException: Provided object is not a plugin instance
        at ~[minecraft_server.1.12.2.jar:?]
        at org.spongepowered.common.scheduler.SpongeScheduler.checkPluginInstance( ~[SpongeScheduler.class:1.12.2-7.1.0-BETA-59]

What should I do to make it work properly? I’ve tried to take a look at working plugins code and tasks were created the same way…

If you want to take a look, here is full code of my plugin main class


You need to either pass in the PluginContainer of your plugin, or the instance of your plugin’s main class.
Since the class RealWeather is you main class (the one with @Plugin), there shouldn’t be an issue passing this to the submit method. I notice that you’re reusing the taskBuilder variable. Typically a builder is only used once, so that could be the cause of your issue. Simply replacing return taskBuilder... with return Sponge.getScheduler().createTaskBuilder()... should be fine.


This solved my problem, thanks :slight_smile:


You don’t need that either. Task.builder() works too. Why do people use the Scheduler directly?


The actual reason for your problem is that Plugin is an annotation, not something your plugin extends. It is a completely different thing from Plugin in Bukkit. If you need to cast at any point, you should use the name of the class that you annotated, not Plugin directly.