|
41 | 41 | import java.util.Objects; |
42 | 42 | import java.util.Optional; |
43 | 43 | import java.util.UUID; |
| 44 | +import java.util.concurrent.Callable; |
| 45 | +import java.util.concurrent.Future; |
| 46 | +import java.util.concurrent.TimeUnit; |
44 | 47 | import java.util.logging.Level; |
45 | 48 |
|
46 | 49 | public final class BankAccounts extends JavaPlugin { |
@@ -383,6 +386,32 @@ public static Optional<String> checkForUpdates() { |
383 | 386 | return Optional.empty(); |
384 | 387 | } |
385 | 388 |
|
| 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 | + |
386 | 415 | public static final class Key { |
387 | 416 | public final static @NotNull NamespacedKey INSTRUMENT_ACCOUNT = namespacedKey("instrument-account"); |
388 | 417 | public final static @NotNull NamespacedKey POS_OWNER_GUI = namespacedKey("pos-owner-gui"); |
|
0 commit comments