-
-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create SchedulerMainThreadBased to simplify implementations
- Loading branch information
Showing
2 changed files
with
61 additions
and
46 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
litecommands-core/src/dev/rollczi/litecommands/scheduler/SchedulerMainThreadBased.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package dev.rollczi.litecommands.scheduler; | ||
|
||
import dev.rollczi.litecommands.shared.ThrowingSupplier; | ||
import java.time.Duration; | ||
import java.util.concurrent.CompletableFuture; | ||
|
||
public abstract class SchedulerMainThreadBased implements Scheduler { | ||
|
||
@Override | ||
public final <T> CompletableFuture<T> supplyLater(SchedulerPoll type, Duration delay, ThrowingSupplier<T, Throwable> supplier) { | ||
SchedulerPoll resolved = type.resolve(SchedulerPoll.MAIN, SchedulerPoll.ASYNCHRONOUS); | ||
CompletableFuture<T> future = new CompletableFuture<>(); | ||
|
||
if (resolved.equals(SchedulerPoll.MAIN)) { | ||
runSynchronous(() -> tryRun(type, future, supplier), delay); | ||
return future; | ||
} | ||
|
||
if (resolved.equals(SchedulerPoll.ASYNCHRONOUS)) { | ||
runAsynchronous(() -> tryRun(type, future, supplier), delay); | ||
return future; | ||
} | ||
|
||
throw new IllegalArgumentException("Unknown scheduler poll type: " + type); | ||
} | ||
|
||
abstract protected void runSynchronous(Runnable task, Duration delay); | ||
|
||
protected abstract void runAsynchronous(Runnable task, Duration delay); | ||
|
||
private <T> void tryRun(SchedulerPoll type, CompletableFuture<T> future, ThrowingSupplier<T, Throwable> supplier) { | ||
try { | ||
future.complete(supplier.get()); | ||
} | ||
catch (Throwable throwable) { | ||
future.completeExceptionally(throwable); | ||
|
||
if (type.isLogging()) { | ||
this.log(throwable); | ||
} | ||
} | ||
} | ||
|
||
protected void log(Throwable throwable) {} | ||
|
||
} |