feature(task): Implement pause, resume and cancel

Use as `pauseTask(taskName)`. They return boolean values to tell the developer if a timed task can be paused/resumed/cancelled properly.
A little bit of testing shows that pausing and then resuming may execute the task multiple times.
This commit is contained in:
Yazawazi 2022-05-08 21:07:37 +08:00 committed by Melledy
parent 9fc4b916c8
commit 5d1f49579b
2 changed files with 35 additions and 3 deletions

View File

@ -1,7 +1,5 @@
package emu.grasscutter.task; package emu.grasscutter.task;
import org.quartz.JobDataMap;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;

View File

@ -67,6 +67,40 @@ public final class TaskMap {
return this; return this;
} }
public boolean pauseTask(String taskName) {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.pauseJob(new JobKey(taskName));
} catch (SchedulerException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean resumeTask(String taskName) {
try {
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.resumeJob(new JobKey(taskName));
} catch (SchedulerException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean cancelTask(String taskName) {
Task task = this.annotations.get(taskName);
if (task == null) return false;
try {
this.unregisterTask(this.tasks.get(taskName));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public TaskMap registerTask(String taskName, TaskHandler task) { public TaskMap registerTask(String taskName, TaskHandler task) {
Task annotation = task.getClass().getAnnotation(Task.class); Task annotation = task.getClass().getAnnotation(Task.class);
this.annotations.put(taskName, annotation); this.annotations.put(taskName, annotation);
@ -116,7 +150,7 @@ public final class TaskMap {
classes.forEach(annotated -> { classes.forEach(annotated -> {
try { try {
Task taskData = annotated.getAnnotation(Task.class); Task taskData = annotated.getAnnotation(Task.class);
Object object = annotated.newInstance(); Object object = annotated.getDeclaredConstructor().newInstance();
if (object instanceof TaskHandler) { if (object instanceof TaskHandler) {
this.registerTask(taskData.taskName(), (TaskHandler) object); this.registerTask(taskData.taskName(), (TaskHandler) object);
if (taskData.executeImmediatelyAfterReset()) { if (taskData.executeImmediatelyAfterReset()) {