### Using MyPlugin.newChain() to start a TaskChain Source: https://github.com/aikar/taskchain/wiki/Implementing-Sponge Shows how to start a new TaskChain anywhere in your plugin after setting up the factory and static helpers as shown in the previous example. ```java MyPlugin.newChain()./* tasks */.execute(); ``` -------------------------------- ### TaskChainExample.java - TaskChain usage example Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChainExample.html Complete Java example of TaskChain usage, including shared chains, task data, futures, and abort behavior. Demonstrates creating a shared chain with delay, sync, async, and abort tasks; using futures with syncFutures and currentLast; and posting an async task that appends a second shared chain and uses returnData with abortIfNull. ```java 001/* 002 * Copyright (c) 2016-2017 Daniel Ennis (Aikar) - MIT License 003 * 004 * Permission is hereby granted, free of charge, to any person obtaining 005 * a copy of this software and associated documentation files (the 006 * "Software"), to deal in the Software without restriction, including 007 * without limitation the rights to use, copy, modify, merge, publish, 008 * distribute, sublicense, and/or sell copies of the Software, and to 009 * permit persons to whom the Software is furnished to do so, subject to 010 * the following conditions: 011 * 012 * The above copyright notice and this permission notice shall be 013 * included in all copies or substantial portions of the Software. 014 * 015 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 016 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 017 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 018 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 019 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 020 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 021 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 022 */ 023 024package co.aikar.taskchain; 025 026import java.util.ArrayList; 027import java.util.List; 028import java.util.concurrent.CompletableFuture; 029import java.util.stream.Collectors; 030 031public class TaskChainExample { 032 /** 033 * A useless example of registering multiple task signatures and states 034 */ 035 public static void example(TaskChainFactory factory) { 036 TaskChainUtil.log("Starting example"); 037 final AsyncQueue asyncQueue = factory.getImplementation().getAsyncQueue(); 038 039 CompletableFuture f1 = new CompletableFuture<>(); // 5 040 CompletableFuture f2 = new CompletableFuture<>(); // 3 041 CompletableFuture f3 = new CompletableFuture<>(); // 8 042 043 TaskChain chain = factory.newSharedChain("TEST"); 044 chain 045 .delay(20 * 3) 046 .sync(() -> { 047 chain.setTaskData("test", 1); 048 TaskChainUtil.log("==> 1st test - completing f3 with 8"); 049 f3.complete(8); 050 }) 051 .delay(20) 052 .async(() -> { 053 Object test = chain.getTaskData("test"); 054 TaskChainUtil.log("==> 2nd test: " + test + " = should be 1"); 055 }) 056 .sync(TaskChain::abort) 057 .execute((finished) -> TaskChainUtil.log("first test finished: " + finished)); 058 059 CompletableFuture falready = new CompletableFuture<>(); 060 falready.complete("FOO!"); 061 factory.newChain() 062 .current(() -> TaskChainUtil.log("Starting Future task")) 063 .futures(f1, f2, f3) 064 .syncFutures((lists) -> { 065 final Integer sum = lists.stream().collect(Collectors.summingInt(i -> i)); 066 TaskChainUtil.log("Future complete! got " + lists.size() + " answers that sum to (expect 16): " + sum); 067 List> ret = new ArrayList<>(); 068 CompletableFuture other = new CompletableFuture<>(); 069 asyncQueue.postAsync(() -> other.complete("Result: " + sum)); 070 ret.add(falready); 071 ret.add(other); 072 return ret; 073 }) 074 .currentLast((results) -> { 075 TaskChainUtil.log("Results from last future task"); 076 for (String result : results) { 077 TaskChainUtil.log(result); 078 } 079 }) 080 .execute(); 081 082 // This chain essentially appends onto the previous one, and will not overlap 083 asyncQueue.postAsync(() -> { 084 TaskChain chain2 = factory.newSharedChain("TEST"); 085 chain2 086 .sync(() -> { 087 Object test = chain2.getTaskData("test"); 088 TaskChainUtil.log("==> 3rd test: " + test + " = should be null"); 089 }) 090 .delay(20) 091 .current(() -> { 092 TaskChainUtil.log("test 2nd chain 20 ticks later - completing f2 with 3"); 093 f2.complete(3); 094 }) 095 .execute((finished) -> TaskChainUtil.log("second test finished: " + finished)); 096 097 factory 098 .newSharedChain("TEST") 099 .async(() -> TaskChainUtil.log("==> 4th test - should print")) 100 .returnData("notthere") 101 .abortIfNull() 102 .syncLast((val) -> TaskChainUtil.log("Shouldn't execute due to null abort")) ``` -------------------------------- ### Shared Output Example Source: https://github.com/aikar/taskchain/wiki/Shared-Task-Chains Shows the output with shared chains: the first chain completes fully (including its delay) before the second chain starts. ```text Hello wait 10 World Foo wait 10 Bar ``` -------------------------------- ### TaskChain example with shared chains, data, and error handling Source: https://github.com/aikar/taskchain/wiki/Usage Complete example of using TaskChain to build and execute chains with shared data, delays, async/sync tasks, callbacks, error handling, and abort conditions. Demonstrates shared chains, data storage/retrieval, and error handling with a custom exception handler. ```java public class TaskChainExample { public static void example(TaskChainFactory factory) { TaskChainUtil.log("Starting example"); TaskChain chain = factory.newSharedChain("TEST"); chain .delay(20 * 3) .sync(() -> { Object test = chain.setTaskData("test", 1); TaskChainUtil.log("==> 1st test"); }) .delay(20) .async(() -> { Object test = chain.getTaskData("test"); TaskChainUtil.log("==> 2nd test: " + test + " = should be 1"); }) .sync(TaskChain::abort) .execute((finished) -> TaskChainUtil.log("first test finished: " + finished)); // This chain essentially appends onto the previous one, and will not overlap factory.getImplementation().postAsync(() -> { TaskChain chain2 = factory.newSharedChain("TEST"); chain2 .sync(() -> { Object test = chain2.getTaskData("test"); TaskChainUtil.log("==> 3rd test: " + test + " = should be null"); }) .delay(20) .current(() -> TaskChainUtil.log("test 2nd chain 20 ticks later")) .execute((finished) -> TaskChainUtil.log("second test finished: " + finished)); factory .newSharedChain("TEST") .async(() -> TaskChainUtil.log("==> 4th test - should print")) .returnData("notthere") .abortIfNull() .syncLast((val) -> TaskChainUtil.log("Shouldn't execute due to null abort")) .execute(() -> TaskChainUtil.log("finished runnable based test")); }); factory .newSharedChain("TEST2") .delay(20 * 3) .sync(() -> TaskChainUtil.log("this should run at same time as 1st test")) .delay(20) .async(() -> TaskChainUtil.log("this should run at same time as 2nd test")) .execute((finished) -> TaskChainUtil.log("TEST2 finished: " + finished)); factory.newChain() .asyncFirst(() -> 42) .asyncLast((i) -> { throw new RuntimeException("Got " + i); }) .execute((finished) -> TaskChainUtil.log("Finished error chain: " + finished), (e, task) -> { TaskChainUtil.logError("Got Exception on task " + task.getClass().getName() + ":" + e.getMessage()); }); factory .newChain() .sync(() -> TaskChainUtil.log("THE FIRST!")) .delay(20 * 10) // Wait 20s to start any task .async(() -> TaskChainUtil.log("This ran async - with no input or return")) .asyncFirstCallback(next -> { // Use a callback to provide result TaskChainUtil.log("this also ran async, but will call next task in 3 seconds."); factory.getImplementation().scheduleTask(60, () -> next.accept(3)); }) .sync(input -> { // Will be ran 3s later but didn't use .delay() TaskChainUtil.log("should have got 3: " + input); return 5 + input; }) .storeAsData("Test1") .syncLast(input2 -> TaskChainUtil.log("should be 8: " + input2)) // Consumes last result, but doesn't pass a new one .delay(20) // Wait 1s until next .sync(() -> TaskChainUtil.log("Generic 1s later")) // no input expected, no output, run sync .asyncFirst(() -> 3) // Run task async and return 3 .delay(5 * 20) // Wait 5s .asyncLast(input1 -> TaskChainUtil.log("async last value 5s later: " + input1)) // Run async again, with value of 3 .returnData("Test1") .asyncLast((val) -> TaskChainUtil.log("Should have got 8 back from data: " + val)) .returnData("Test1") .abortIf(8) .sync(() -> TaskChainUtil.log("Shouldn't be called")) .execute((finished) -> TaskChainUtil.log("final test chain finished: " + finished)); } } ``` -------------------------------- ### Creating a TaskChain factory in a Sponge plugin Source: https://github.com/aikar/taskchain/wiki/Implementing-Sponge Example of integrating TaskChain into a Sponge plugin by creating a TaskChainFactory and providing static helper methods. Note: the onServerStart method in the source appears to be missing an opening brace after the event parameter, and the code may not compile as displayed. ```java import co.aikar.taskchain.SpongeTaskChainFactory; import co.aikar.taskchain.TaskChainFactory; import co.aikar.taskchain.TaskChain; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.game.state.GameStartedServerEvent; @Plugin(id = "myplugin", name = "My Plugin", version = "1.0") public class MyPlugin extends JavaPlugin { private static TaskChainFactory taskChainFactory; public static TaskChain newChain() { return taskChainFactory.newChain(); } public static TaskChain newSharedChain(String name) { return taskChainFactory.newSharedChain(name); } @Listener public void onServerStart(GameStartedServerEvent event) taskChainFactory = SpongeTaskChainFactory.create(this); } } ``` -------------------------------- ### Non-Shared Output Example Source: https://github.com/aikar/taskchain/wiki/Shared-Task-Chains Shows the output if the chains were not shared: the first chain's async tasks run, then the second chain's, with delays interleaved. ```text Hello Foo wait 10 World Bar ``` -------------------------------- ### Shared Chain Pseudocode Example Source: https://github.com/aikar/taskchain/wiki/Shared-Task-Chains Shows two shared chains with the same name 'test'. Without sharing, the output would be interleaved; with sharing, the chains execute sequentially, each completing its delay before the next starts. ```pseudocode newSharedChain("test") (async) -> print("Hello") (delay) -> 10 seconds (async) -> print("World") newSharedChain("test") (async) -> print("Foo") (delay) -> 10 seconds (async) -> print("Bar") ``` -------------------------------- ### Java plugin integration with TaskChainFactory Source: https://github.com/aikar/taskchain/wiki/Implementing-Bukkit Example Java plugin class that creates a TaskChainFactory and provides static helper methods to create new chains. Call BukkitTaskChainFactory.create(this) in onEnable() to initialize the factory. The static methods newChain() and newSharedChain(String name) can then be used anywhere in the plugin. ```java import co.aikar.taskchain.BukkitTaskChainFactory; import co.aikar.taskchain.TaskChainFactory; import co.aikar.taskchain.TaskChain; import org.bukkit.plugin.java.JavaPlugin; public class MyPlugin extends JavaPlugin { private static TaskChainFactory taskChainFactory; public static TaskChain newChain() { return taskChainFactory.newChain(); } public static TaskChain newSharedChain(String name) { return taskChainFactory.newSharedChain(name); } @Override public void onEnable() { taskChainFactory = BukkitTaskChainFactory.create(this); } } ``` -------------------------------- ### Gradle setup for TaskChain Sponge Source: https://github.com/aikar/taskchain/wiki/Implementing-Sponge Gradle build configuration for adding the TaskChain Sponge dependency. Requires adding the Aikar and Sponge repositoriesasixtures and shadowing the library into your plugin jar. Replace with the latest version from the TaskChain home page. ```gradle buildscript { repositories { jcenter() } dependencies { classpath "com.github.jengelman.gradle.plugins:shadow:1.2.4" } } apply plugin: "com.github.johnrengelman.shadow" repositories { maven { url = "https://repo.aikar.co/content/groups/aikar/" } maven { url "http://repo.spongepowered.org/maven/" } } dependencies { compile "co.aikar:taskchain-sponge:" } build.dependsOn shadowJar ``` -------------------------------- ### Maven setup for TaskChain Sponge Source: https://github.com/aikar/taskchain/wiki/Implementing-Sponge Maven pom.xml configuration for adding the TaskChain Sponge dependency. Requires adding Aikar and Sponge repositories and shading the library into your plugin jar. Replace TASKCHAIN VERSION with the latest version from the TaskChain home page. ```xml 4.0.0 aikar http://ci.emc.gs/nexus/content/groups/aikar/ sponge-maven-repo Sponge maven repo http://repo.spongepowered.org/maven true true co.aikar taskchain-sponge TASKCHAIN VERSION org.apache.maven.plugins maven-shade-plugin 2.4.1 ${project.build.directory}/dependency-reduced-pom.xml package shade ``` -------------------------------- ### GoodExample: TaskChain for clean async operations Source: https://github.com/aikar/taskchain/wiki/Why-TaskChain Shows the same operation implemented with TaskChain, using asyncFirst, sync, and async steps with abortIfNull for error handling. This is the recommended approach. ```java public class GoodExample { TaskChainFactory taskChain; public void someBigOperation(Object player, Object identifier) { taskChain.newChain() .asyncFirst(() -> someLongBlockingRequest(player, identifier)) .abortIfNull(ActionHandlers.MESSAGE, player, "Sorry, something failed!") .sync((result) -> GameAPI.doSomethingToPlayerWithResult(player, result)) .abortIfNull(ActionHandlers.MESSAGE, player, "Sorry, something failed!") .async((opResult) -> markOperationSuccessful(player, identifier, opResult)) .execute(); } } ``` -------------------------------- ### TaskChainTasks.Task Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChainTasks.AsyncExecutingTask.html The Task interface is the base for all task types in the TaskChain library. It defines a synchronous run method and a helper to get the current chain. ```APIDOC ## Interface: TaskChainTasks.Task ### Description Generic task with synchronous return (but may execute on any thread). ### Methods #### `R run(A input)` - **Parameters:** - `input` (A) - The input from the previous task. - **Returns:** - (R) - The result to be passed to the next task. #### `default TaskChain getCurrentChain()` - **Description:** Returns the current chain. - **Returns:** - (TaskChain) - The current chain. ``` -------------------------------- ### run(A input) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.Task.html Executes the task with the given input and returns a result. This is the main method that must be implemented by task implementations. ```APIDOC ## run(A input) ### Description Executes the task with the given input and returns a result. This is the main method that must be implemented by task implementations. ### Method `R run(A input)` ### Parameters - `input` (A) - The input to the task. ### Returns - `R` - The result of the task execution. ``` -------------------------------- ### Task Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChainTasks.html Generic task with synchronous return (but may execute on any thread). It provides a default method to get the current chain and an abstract run method. ```APIDOC ## Task ### Description Generic task with synchronous return (but may execute on any thread). ### Methods - **getCurrentChain()** - Returns the current TaskChain instance. Default implementation calls TaskChain.getCurrentChain(). - **run(A input)** - Abstract method to execute the task with the given input and return a result of type R. ``` -------------------------------- ### TaskChain.execute() Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChain.html Finished adding tasks, begins executing them. ```APIDOC ## TaskChain.execute() ### Description Finished adding tasks, begins executing them. ### Method TaskChain.execute ### Parameters None. ### Returns void ``` -------------------------------- ### TaskChain.asyncFirst(FirstTask) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.asyncFirst. ```APIDOC ## TaskChain.asyncFirst(FirstTask task) ### Description Executes the first task asynchronously off the main thread, with no input, returning an output. This is the async variant of `syncFirst`. ### Method ` TaskChain asyncFirst(TaskChainTasks.FirstTask task)` ### Parameters - **task** (TaskChainTasks.FirstTask) - Required - The first task to execute asynchronously. ### Returns - **TaskChain** - The task chain for chaining subsequent tasks. ``` -------------------------------- ### TaskChainTasks.AsyncExecutingFirstTask Interface Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.AsyncExecutingFirstTask.html Documentation for the TaskChainTasks.AsyncExecutingFirstTask interface, including its methods run(Object), runAsync(Object, Consumer), and run(Consumer). ```APIDOC ## Interface TaskChainTasks.AsyncExecutingFirstTask ### Description This interface represents a task that executes asynchronously and is the first task in a task chain. It extends AsyncExecutingTask and Task, providing methods to run the task with an input and to run it asynchronously with a callback. ### Methods #### run(Object input) **Signature:** `default R run(Object input)` **Description:** Executes the task with the given input and returns a result. This is a default method that may be overridden. **Parameters:** - `input` (Object) - The input to the task. **Returns:** - `R` - The result of the task execution. #### runAsync(Object input, Consumer next) **Signature:** `default void runAsync(Object input, Consumer next)` **Description:** Executes the task asynchronously with the given input and passes the result to the provided consumer callback. This is a default method that may be overridden. **Parameters:** - `input` (Object) - The input to the task. - `next` (Consumer) - The consumer to receive the result of the task. #### run(Consumer next) **Signature:** `void run(Consumer next)` **Description:** Executes the task and passes the result to the provided consumer callback. This method must be implemented by classes implementing this interface. **Parameters:** - `next` (Consumer) - The consumer to receive the result of the task. ``` -------------------------------- ### TaskChain.syncFirst(FirstTask) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.syncFirst. ```APIDOC ## TaskChain.syncFirst(FirstTask task) ### Description Executes the first task on the main thread, with no input, returning an output. ### Method ` TaskChain syncFirst(TaskChainTasks.FirstTask task)` ### Parameters - **task** (TaskChainTasks.FirstTask) - Required - The first task to execute on the main thread. ### Returns - **TaskChain** - The task chain for chaining subsequent tasks. ``` -------------------------------- ### newChain Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainFactory.html Creates a new TaskChain instance. ```APIDOC ## newChain ### Description Creates a new chain. ### Method `public TaskChain newChain()` ### Returns A new TaskChain instance. ``` -------------------------------- ### TaskChain.currentFirst(FirstTask) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.currentFirst. ```APIDOC ## TaskChain.currentFirst(FirstTask task) ### Description Executes the first task on the current thread the chain was created on, with no input, returning an output. This is the current-thread variant of `syncFirst`. ### Method ` TaskChain currentFirst(TaskChainTasks.FirstTask task)` ### Parameters - **task** (TaskChainTasks.FirstTask) - Required - The first task to execute on the current thread. ### Returns - **TaskChain** - The task chain for chaining subsequent tasks. ``` -------------------------------- ### configure Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChain.html Allows inserting tasks into the chain via a callback without breaking the fluent interface. ```APIDOC ## configure ### Description Allows you to call a callback to insert tasks into the chain without having to break the fluent interface. ### Method configure ### Signature `TaskChain configure(Consumer> configure)` ### Parameters - `configure` (Consumer>) - Required - A callback that receives the TaskChain to add tasks. ### Returns - `TaskChain` - The TaskChain for chaining further tasks. ### Example ```java Plugin.newChain() .sync(some::task) .configure(chain -> { chain.async(some::foo); chain.sync(other::bar); }) .async(other::task) .execute(); ``` ``` -------------------------------- ### run(Object input) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.AsyncExecutingGenericTask.html Executes the task with the given input and returns the result. This is a default method that can be overridden. ```APIDOC ## Method: run(Object input) ### Description Executes the task with the provided input and returns the result. This is a default method that can be overridden by implementations. ### Method run ### Signature `default Object run(Object input)` ### Parameters - **input** (Object) - Required - The input object passed to the task. ### Returns - **Object** - The result of the task execution. ### Example ```java AsyncExecutingGenericTask task = (input) -> { // process input return result; }; Object output = task.run(someInput); ``` ``` -------------------------------- ### AsyncExecutingFirstTask Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChainTasks.AsyncExecutingFirstTask.html Documentation for the AsyncExecutingFirstTask interface, including its abstract method and default implementations. ```APIDOC ## AsyncExecutingFirstTask ### Description An interface for tasks that execute asynchronously and do not require an input, but produce a result of type R. It extends AsyncExecutingTask and provides default implementations for the synchronous and asynchronous methods, delegating to a custom run(Consumer) method. ### Method run(Consumer next) ### Signature void run(Consumer next) ### Parameters - **next** (Consumer) - Required - A consumer that will receive the result of the asynchronous task. ### Description This is the abstract method that must be implemented by users. It should execute the task asynchronously and invoke the provided consumer with the result. ### Default Methods - **run(Object input)** - Returns null, as input is unused. - **runAsync(Object input, Consumer next)** - Calls run(next) to execute the task. ### Usage Example ```java AsyncExecutingFirstTask task = next -> { // Perform async operation next.accept("result"); }; ``` ``` -------------------------------- ### TaskChainTasks.FirstTask Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.FirstTask.html Documentation for the TaskChainTasks.FirstTask interface, including its run() and run(Object) methods. ```APIDOC ## TaskChainTasks.FirstTask ### Description A task that expects no input, and returns a value. Likely to be the first task in the chain. ### Method run() ### Signature R run() ### Parameters None. ### Returns - **R** - The result of the task. ### Example ```java TaskChainTasks.FirstTask firstTask = () -> "Hello"; ``` ``` ```APIDOC ## TaskChainTasks.FirstTask.run(Object input) ### Description Default method that accepts an input object and returns a value. This is the default implementation of the Task interface's run method. ### Method run(Object input) ### Signature default R run(Object input) ### Parameters - **input** (Object) - The input to the task. ### Returns - **R** - The result of the task. ### Example ```java TaskChainTasks.FirstTask firstTask = input -> "Hello"; ``` ``` -------------------------------- ### newChain() Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainFactory.html Creates a new TaskChain instance. ```APIDOC ## newChain() ### Description Creates a new TaskChain instance. ### Method newChain() ### Parameters None ### Returns - **TaskChain** - A new TaskChain instance. ``` -------------------------------- ### TaskChainTasks.AsyncExecutingFirstTask Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.AsyncExecutingFirstTask.html Documentation for the TaskChainTasks.AsyncExecutingFirstTask interface, including its methods for running tasks asynchronously. ```APIDOC ## Interface TaskChainTasks.AsyncExecutingFirstTask ### Description This interface represents a task that executes asynchronously and is the first task in a chain. It extends AsyncExecutingTask and provides methods to run the task with a callback for the result. ### Methods #### run(Consumer next) - **Signature**: `void run(Consumer next)` - **Description**: Executes the task asynchronously and passes the result to the provided consumer. - **Parameters**: - `next` (Consumer) - The consumer that receives the result of the task. #### run(Object input) - **Signature**: `default R run(Object input)` - **Description**: Runs the task synchronously with the given input and returns the result. - **Parameters**: - `input` (Object) - The input to the task. - **Returns**: The result of type R. #### runAsync(Object input, Consumer next) - **Signature**: `default void runAsync(Object input, Consumer next)` - **Description**: Runs the task asynchronously with the given input and passes the result to the consumer. - **Parameters**: - `input` (Object) - The input to the task. - `next` (Consumer) - The consumer that receives the result. ``` -------------------------------- ### AsyncExecutingFirstTask Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChainTasks.FutureFirstTask.html Documentation for the AsyncExecutingFirstTask interface, including its methods and their signatures. ```APIDOC ## AsyncExecutingFirstTask ### Description Interface for a task that executes asynchronously and produces a result. It extends AsyncExecutingTask and provides default implementations for the synchronous and asynchronous methods, delegating to the abstract run(Consumer) method. ### Methods #### run(Object input) - **Signature**: `default R run(Object input)` - **Description**: Default implementation that returns null. The input parameter is unused. - **Parameters**: - `input` (Object) - Unused. - **Returns**: `R` - Always null. #### runAsync(Object input, Consumer next) - **Signature**: `default void runAsync(Object input, Consumer next)` - **Description**: Default implementation that calls `run(next)`. - **Parameters**: - `input` (Object) - Unused. - `next` (Consumer) - The consumer to receive the result. #### run(Consumer next) - **Signature**: `void run(Consumer next)` - **Description**: Abstract method to be implemented by users. Executes the task asynchronously and passes the result to the provided consumer. - **Parameters**: - `next` (Consumer) - The consumer to receive the result. ``` -------------------------------- ### getImplChain() Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/BaseTaskChain.html Returns the underlying implementation chain. ```APIDOC ## getImplChain() ### Description Returns the implementation chain instance. ### Method BaseTaskChain getImplChain() ### Return Type BaseTaskChain ``` -------------------------------- ### UglyExample: Nested callbacks for async game API operations Source: https://github.com/aikar/taskchain/wiki/Why-TaskChain Shows a typical solution using an ExecutorService and a game scheduler, with nested callbacks to switch threads. This is the 'ugly' version that TaskChain aims to replace. ```java public class UglyExample { ExecutorService threadPool; public void someBigOperation(Object player, Object identifier) { threadPool.submit(() -> { Object result = someLongBlockingRequest(player, identifier); if (result == null) { sendPlayerMessage(player, "Sorry, something failed!"); return; } GameScheduler.runTaskOnMain( () -> { Object opResult = GameAPI.doSomethingToPlayerWithResult(player, result); if (opResult == null) { sendPlayerMessage(player, "Sorry, something failed!"); return; } threadPool.submit(() -> { markOperationSuccessful(player, identifier, opResult); }); }); }); } } ``` -------------------------------- ### TaskChain.configure(Consumer>) Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChain.html Instance method to configure the chain with a callback. ```APIDOC ## TaskChain.configure(Consumer>) ### Description Allows you to call a callback to insert tasks into the chain without having to break the fluent interface. ### Method `configure` ### Signature `public TaskChain configure(Consumer> configure)` ### Parameters - `configure` (Consumer>) - Required - A consumer that receives the current chain instance. ### Returns `TaskChain` - The same chain instance. ``` -------------------------------- ### TaskChain.execute(Runnable done) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChain.html Finished adding tasks, begins executing them with a done notifier. ```APIDOC ## TaskChain.execute(Runnable done) ### Description Finished adding tasks, begins executing them with a done notifier. ### Method TaskChain.execute ### Parameters - `done` (Runnable) - Required - The done notifier to be called when the chain completes. ### Returns void ``` -------------------------------- ### Equivalent Backing Chain Pseudocode Source: https://github.com/aikar/taskchain/wiki/Shared-Task-Chains Shows the equivalent structure of a shared chain as a backing chain that executes each shared chain sequentially using async callbacks. ```pseudocode newChain() (asyncCallback:done) newChain() (async) -> print("Hello") (delay) -> 10 seconds (async) -> print("World") (async) -> done() (execute) (asyncCallback:done) newChain() (async) -> print("Foo") (delay) -> 10 seconds (async) -> print("Bar") (async) -> done() (execute) (execute) ``` -------------------------------- ### TaskChain.asyncFirstCallback(AsyncExecutingFirstTask task) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChain.html Runs the given async executing first task off the main thread. Equivalent to TaskChain#syncFirstCallback(AsyncExecutingFirstTask) but executed asynchronously. ```APIDOC ## TaskChain.asyncFirstCallback(AsyncExecutingFirstTask task) ### Description Runs the given async executing first task off the main thread. Equivalent to TaskChain#syncFirstCallback(AsyncExecutingFirstTask) but executed asynchronously. ### Method asyncFirstCallback ### Parameters - **task** (TaskChainTasks.AsyncExecutingFirstTask) - Required - The task to execute asynchronously. ### Returns - **TaskChain** - A new TaskChain with the result type R. ``` -------------------------------- ### postToMain(Runnable run) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/GameInterface.html Schedule a runnable to run on the main thread. ```APIDOC ## postToMain(Runnable run) ### Description Schedule a runnable to run on the main thread. ### Method postToMain ### Signature ```java void postToMain(Runnable run) ``` ### Parameters - **run** (Runnable) - Required - The runnable to schedule on the main thread. ``` -------------------------------- ### TaskChainTasks.GenericTask Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.GenericTask.html Documentation for the TaskChainTasks.GenericTask interface, including its methods run and runGeneric. ```APIDOC ## Interface TaskChainTasks.GenericTask ### Description A task that expects no input or output. ### Methods #### run(Object input) - **Signature**: `default Object run(Object input)` - **Description**: Runs the task with the given input. This is a default method that delegates to `runGeneric()`. - **Parameters**: - `input` (Object) - The input to the task. - **Returns**: Object - The result of the task. #### runGeneric() - **Signature**: `void runGeneric()` - **Description**: Runs the task without any input or output. - **Parameters**: None - **Returns**: void ``` -------------------------------- ### run(A input) (default) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.FutureTask.html Default method that runs the task synchronously. It is inherited from the Task interface and may be overridden. ```APIDOC ## run(A input) (default) ### Description Default method that runs the task synchronously. It is inherited from the Task interface and may be overridden. ### Method `default R run(A input)` ### Parameters - **input** (A) - Required - The value from the previous task in the chain. ### Returns - **R** - The result of the task. ``` -------------------------------- ### multi Source: https://github.com/aikar/taskchain/blob/master/docs/src-html/co/aikar/taskchain/TaskChain.html Creates a data wrapper to return multiple objects from a task. ```APIDOC ## multi(D1 var1, D2 var2) ### Description Creates a data wrapper to return multiple objects from a task. This is a static method that returns a Data2 wrapper containing the two provided values. ### Method `static TaskChainDataWrappers.Data2 multi(D1 var1, D2 var2)` ### Parameters - **var1** (D1) - Required - The first value to wrap. - **var2** (D2) - Required - The second value to wrap. ### Returns - **TaskChainDataWrappers.Data2** - A data wrapper containing the two values. ``` -------------------------------- ### runAsync(Object input, Consumer next) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.AsyncExecutingGenericTask.html Asynchronously executes the task with the given input and invokes the callback with the result. This is a default method that can be overridden. ```APIDOC ## Method: runAsync(Object input, Consumer next) ### Description Asynchronously executes the task with the provided input and invokes the callback with the result. This is a default method that can be overridden by implementations. ### Method runAsync ### Signature `default void runAsync(Object input, Consumer next)` ### Parameters - **input** (Object) - Required - The input object passed to the task. - **next** (Consumer) - Required - The callback to receive the result. ### Returns - void ### Example ```java AsyncExecutingGenericTask task = (input, callback) -> { // perform async work callback.accept(result); }; task.runAsync(someInput, result -> { // handle result }); ``` ``` -------------------------------- ### TaskChain.multi(D1, D2, D3, D4, D5) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainDataWrappers.Data5.html Documentation for the TaskChain.multi method that creates a data wrapper for multiple objects. ```APIDOC ## TaskChain.multi(D1, D2, D3, D4, D5) ### Description Creates a data wrapper to return multiple objects from a task. ### Method multi ### Signature `static TaskChainDataWrappers.Data5 multi(D1 var1, D2 var2, D3 var3, D4 var4, D5 var5)` ### Parameters - **var1** (D1) - Required - First object to wrap. - **var2** (D2) - Required - Second object to wrap. - **var3** (D3) - Required - Third object to wrap. - **var4** (D4) - Required - Fourth object to wrap. - **var5** (D5) - Required - Fifth object to wrap. ### Return Value - **TaskChainDataWrappers.Data5** - A data wrapper containing the five provided objects. ``` -------------------------------- ### TaskChain.asyncFirstFutures(FirstTask>>) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.asyncFirstFutures. ```APIDOC ## TaskChain.asyncFirstFutures(FirstTask>> task) ### Description Executes a task off the main thread that provides a list of Futures, and holds processing of the chain until all of the futures complete. ### Method ` TaskChain> asyncFirstFutures(TaskChainTasks.FirstTask>> task)` ### Parameters - **task** (TaskChainTasks.FirstTask>>) - Required - The first task that returns a list of futures. ### Returns - **TaskChain>** - The task chain that will continue after all futures complete. ``` -------------------------------- ### TaskChain.asyncFirst(FirstTask task) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChain.html Runs the given first task off the main thread. Equivalent to TaskChain#syncFirst(FirstTask) but executed asynchronously. ```APIDOC ## TaskChain.asyncFirst(FirstTask task) ### Description Runs the given first task off the main thread. Equivalent to TaskChain#syncFirst(FirstTask) but executed asynchronously. ### Method asyncFirst ### Parameters - **task** (TaskChainTasks.FirstTask) - Required - The task to execute asynchronously. ### Returns - **TaskChain** - A new TaskChain with the result type R. ``` -------------------------------- ### TaskChain.syncFirstFutures(FirstTask>>) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.syncFirstFutures. ```APIDOC ## TaskChain.syncFirstFutures(FirstTask>> task) ### Description Executes a task on the main thread that provides a list of Futures, and holds processing of the chain until all of the futures complete. ### Method ` TaskChain> syncFirstFutures(TaskChainTasks.FirstTask>> task)` ### Parameters - **task** (TaskChainTasks.FirstTask>>) - Required - The first task that returns a list of futures. ### Returns - **TaskChain>** - The task chain that will continue after all futures complete. ``` -------------------------------- ### runFuture(A input) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.FutureTask.html Executes the task and returns a CompletableFuture that will complete with the result. The input is the value from the previous task in the chain. ```APIDOC ## runFuture(A input) ### Description Executes the task and returns a CompletableFuture that will complete with the result. The input is the value from the previous task in the chain. ### Method `CompletableFuture runFuture(A input)` ### Parameters - **input** (A) - Required - The value from the previous task in the chain. ### Returns - **CompletableFuture** - A future that will complete with the result of type R. ``` -------------------------------- ### TaskChain.currentFirstFutures(FirstTask>>) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/class-use/TaskChainTasks.FirstTask.html Method signature and description for TaskChain.currentFirstFutures. ```APIDOC ## TaskChain.currentFirstFutures(FirstTask>> task) ### Description Executes a task on the current thread that provides a list of Futures, and holds processing of the chain until all of the futures complete. ### Method ` TaskChain> currentFirstFutures(TaskChainTasks.FirstTask>> task)` ### Parameters - **task** (TaskChainTasks.FirstTask>>) - Required - The first task that returns a list of futures. ### Returns - **TaskChain>** - The task chain that will continue after all futures complete. ``` -------------------------------- ### TaskChain.execute(Consumer done) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChain.html Finished adding tasks, with a done notifier. ```APIDOC ## TaskChain.execute(Consumer done) ### Description Finished adding tasks, with a done notifier. ### Method TaskChain.execute ### Parameters - `done` (Consumer) - Required - The done notifier to be called when the chain completes. ### Returns void ``` -------------------------------- ### run(A input) Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.AsyncExecutingTask.html Default method that runs the task synchronously. It is specified by the Task interface and returns a result of type R. ```APIDOC ## run(A input) ### Description Default method that runs the task synchronously. It is specified by the Task interface and returns a result of type R. ### Method run ### Signature `default R run(A input)` ### Parameters - **input** (A) - The input to the task. ### Returns - **R** - The result of the task. ``` -------------------------------- ### TaskChainTasks.FutureFirstTask Source: https://github.com/aikar/taskchain/blob/master/docs/co/aikar/taskchain/TaskChainTasks.FutureFirstTask.html Documentation for the TaskChainTasks.FutureFirstTask interface, including its methods and inherited methods. ```APIDOC ## Interface TaskChainTasks.FutureFirstTask ### Description A Task that returns a future to be completed later. Expects no input, and when the future completes, the value will be passed to the next task. ### Methods #### runFuture() - **Signature**: `CompletableFuture runFuture()` - **Description**: Returns a future to be completed later. This method is the primary method for this interface. #### runFuture(Object input) - **Signature**: `default CompletableFuture runFuture(Object input)` - **Description**: A default method that accepts an input object and returns a future. This method is specified by the parent interface `TaskChainTasks.FutureTask`. ### Inherited Methods - From `TaskChainTasks.FutureTask`: `run(A)` - From `TaskChainTasks.Task`: `getCurrentChain()` ``` -------------------------------- ### Java open() and unlockPackage() Methods Using Shared Chains Source: https://github.com/aikar/taskchain/wiki/Shared-Task-Chains Two methods that use shared chains to ensure that opening a package occurs after any pending save and unlock operations. The open method uses a callback, and the unlock method updates the database. ```java public synchronized void open(Player player, Consumer cb) { Empire.newSharedChain(chainName).async( () -> { if (openedPackage == null) { openedPackage = OpenedPackage.tryOpen(player, this); } cb.accept(openedPackage); }).execute(); } void unlockPackage() { Empire.newSharedChain(chainName).async( () -> { try { EmpireDb.executeUpdate("UPDATE packages SET open_on = 0 WHERE id = ?", packageId); } catch (SQLException e) { Util.printException(e); } }).execute(); } ```