How to use Scheduler within static context?

I.e. a static method, which contains the line

Task.builder().execute(Runnables.doNothing()).delay(1, TimeUnit.SECONDS).submit(this);

If I write this code inside a static method, the IDE highlights “this” and says:

‘myPackage.Main.this’ cannot be referenced from a static context

“this” in java, means this instance, when you are in static form there is no “this” because there is no instance.

The easiest way around the issue your having is to do the following

static YourMainClass plugin;

@Listener
public void onEnable(GameStartingServerEvent event){
    plugin = this;
}

public static YourMainClass getInstance(){
    return plugin;
} 

So now replace the “this” with

YourMainClass.getInstance()

The build option also accepts PluginContainer if you wish to use that

2 Likes