Best way to let a scheduler run in a new thread

Hey,
as I know, it’s better, when I create a new thread for “heavy” calculations in combination with database connections.
The scheduler is placed in a new class, which gets called / created on GameStartedServerEvent with new TaxScheduler(this, logger);

Scheduler class:

public TaxScheduler(Main plugin, Logger logger) throws IOException {
	Scheduler scheduler = Sponge.getGame().getScheduler();
	Task.Builder taskBuilder = scheduler.createTaskBuilder();

	taskBuilder.execute(new Runnable() {
		public void run() {
                //code
		}

	}).interval(60, TimeUnit.SECONDS).name("Tax Updater").submit(plugin);
}

My code works, but I want to open it in a new thread. I did this before, but I’m new to java and don’t know the best way to do this.

Is there a better way, or is it “ok”, when I do it like this:

new Thread()
        {
            public void run() {
                try {
                    new TaxScheduler(plugin, logger);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

Greets :slight_smile:

1 Like

Use the first method, but call the async() method on the builder.

2 Likes

So this method will run my scheduler in a new thread?
(Right?) Example:
Task.Builder taskBuilder = scheduler.createTaskBuilder().async();

Exactly. Calling async().submit(...) on a TaskBuilder executes the task in a new (or pooled) thread. That’s in most cases faster than creating your own thread. But keep in mind that most parts of the Sponge API are not thread safe!

1 Like

It may be useful to read the javadoc for async() so that you understand what it actually means.
https://jd.spongepowered.org/3.0.0/org/spongepowered/api/scheduler/Task.Builder.html#async--

1 Like