Skip to content

Commit 76cd84e

Browse files
committed
method to run code on main thread
1 parent 6a1b1fd commit 76cd84e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/main/java/pro/cloudnode/smp/bankaccounts/BankAccounts.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@
4141
import java.util.Objects;
4242
import java.util.Optional;
4343
import java.util.UUID;
44+
import java.util.concurrent.Callable;
45+
import java.util.concurrent.Future;
46+
import java.util.concurrent.TimeUnit;
4447
import java.util.logging.Level;
4548

4649
public final class BankAccounts extends JavaPlugin {
@@ -383,6 +386,32 @@ public static Optional<String> checkForUpdates() {
383386
return Optional.empty();
384387
}
385388

389+
/**
390+
* Run a task on the main thread
391+
* @param task The task to run
392+
* @param timeout Task timeout in SECONDS. Set to 0 to disable timeout
393+
*/
394+
public static <T> @NotNull Optional<T> runOnMain(@NotNull Callable<T> task, final long timeout) {
395+
final @NotNull BankAccounts plugin = BankAccounts.getInstance();
396+
final @NotNull Future<T> future = plugin.getServer().getScheduler().callSyncMethod(plugin, task);
397+
try {
398+
if (timeout == 0) return Optional.of(future.get());
399+
return Optional.of(future.get(timeout, TimeUnit.SECONDS));
400+
}
401+
catch (final @NotNull Exception e) {
402+
plugin.getLogger().log(Level.WARNING, "Failed to run task on main thread", e);
403+
}
404+
return Optional.empty();
405+
}
406+
407+
/**
408+
* Run a task on the main thread (without timeout)
409+
* @param task The task to run
410+
*/
411+
public static <T> @NotNull Optional<T> runOnMain(@NotNull Callable<T> task) {
412+
return runOnMain(task, 0);
413+
}
414+
386415
public static final class Key {
387416
public final static @NotNull NamespacedKey INSTRUMENT_ACCOUNT = namespacedKey("instrument-account");
388417
public final static @NotNull NamespacedKey POS_OWNER_GUI = namespacedKey("pos-owner-gui");

0 commit comments

Comments
 (0)