我正在尝试安排一堆任务定期执行。在某些情况下,某些任务需要停止调度,所以我将它们从 threadPoolExecutor 的内部队列中删除。我从任务本身中做到这一点
下面是我的方法。我不确定从 threadPoolExecutor 服务中删除任务的想法,从任务内部会导致任何问题。(查看同步方法名称“removeTask”。有没有更好的方法来完成我在这里尝试做的事情.
public class SchedulerDaemon {
private ScheduledExecutorService taskScheduler;
private ScheduledFuture taskResult1, taskResult2;
private Task1 task1;
private Task2 task2;
public SchedulerDaemon(Task1 task, Task2 task2)
{
this.task1 = task1;
this.task2 = task2;1
taskScheduler = new ScheduledThreadPoolExecutor(1);
}
public void start() {
if(taskScheduler == null) {
taskScheduler = new ScheduledThreadPoolExecutor(1);
taskResult = taskScheduler.scheduleAtFixedRate(new TaskWrapper(task1) , 60000,60000, TimeUnit.MILLISECONDS);
taskResult2 = taskScheduler.scheduleAtFixedRate(new TaskWrapper(task2) , 60000,60000, TimeUnit.MILLISECONDS);
}
}
public void stop() {
if(taskScheduler != null) {
taskScheduler.shutdown();
taskResult1.cancel(false);
taskResult2.cancel(false);
taskScheduler = null;
taskResult = null;
}
}
public synchronized void removeTask( TaskWrapper task){
((ScheduledThreadPoolExecutor) taskScheduler).remove(task);
}
class TaskWrapper implements Runnable {
private Task myTask;
public TaskWrapper(Task task) {
myTask = task;
}
@Override
public void run() {
try {
boolean keepRunningTask = myTask.call();
if(!keepRunningTask) {
***//Should this cause any problem??***
removeTask(this);
}
} catch (Exception e) {
//the task threw an exception remove it from execution queue
***//Should this cause any problem??***
removeTask(this);
}
}
}
}
public Task1 implements Callable<Boolean> {
public Boolean call() {
if(<something>)
return true;
else
return false;
}
}
public Task2 implements Callable<Boolean> {
public Boolean call() {
if(<something>)
return true;
else
return false;
}
}