base.task.TaskManager Maven / Gradle / Ivy
/**
* Creative commons Attribution-NonCommercial license.
*
* http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
*
* NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
*/
package base.task;
import base.jee.api.Settings;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TaskManager {
private static Map taskHandlers = new HashMap<>();
/**
* Register that a task should be executed regularly at a specific interval.
*
* @param name Unique name identifying the task
* @param interval How frequently the task should be executed in seconds
* @param task The task that should be executed regularly
*/
public static void registerRegularTask(String name, int interval, Task task) {
if(taskHandlers.containsKey(name)) {
throw new IllegalStateException("Attempted to register a task named " + name + " when a task with this name already exists.");
}
RegularTaskHandler handler = new RegularTaskHandler(name, task, interval);
taskHandlers.put(name, handler);
handler.start();
}
/**
* Register that a task should be executed regularly at a specific interval.
*
* @param name Unique name identifying the task
* @param daysOfMonth Which days of the month this task will run (null/empty means every day)
* @param daysOfWeek Which days of the week this task will run (null/empty means every day)
* @param hoursOfDay Which hours of the day this task will run (null/empty means every hour)
* @param task The task that should be executed regularly
* @throws IOException
*/
public static void registerScheduledTask(String name, int[]daysOfMonth, int[] daysOfWeek, int[] hoursOfDay, Task task, Settings settings) throws IOException {
if(taskHandlers.containsKey(name)) {
throw new IllegalStateException("Attempted to register a task named " + name + " when a task with this name already exists.");
}
ScheduledTaskHandler handler = new ScheduledTaskHandler(name, task, daysOfMonth, daysOfWeek, hoursOfDay, settings);
taskHandlers.put(name, handler);
handler.start();
}
public static void unregisterRegularTask(String name) throws InterruptedException {
TaskHandler handler = null;
if(taskHandlers.containsKey(name)) {
handler = taskHandlers.remove(name);
handler.shutdown();
handler.join();
}
}
/**
* Called when either java process is being terminated, to clean up any Task's that are still
* scheduled to be executed.
*/
public static void shutdown() throws InterruptedException {
for(TaskHandler handler : taskHandlers.values()) {
handler.shutdown();
handler.join();
}
taskHandlers.clear();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy