英文:
How to cancel ThreadPoolTaskExecutor task
问题
我已经将作业提交给了Spring
的ThreadPoolTaskExecutor
:
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
private Map<String, Runnable> runningTasks = new HashMap<>();
public String doSomeTask() {
Runnable job = new MyJob();
String id = RandomStringUtils.randomAlphanumeric(32);
taskExecutor.execute(job);
runningTasks.put(id, job);
return id;
}
现在我想要取消一些作业。我有可运行的对象,但它没有interrupt()
方法,因为线程是由执行器管理的。但我找不到在ThreadPoolTaskExecutor
上取消给定作业的方法。
我是否忽略了一些明显的东西,或者我选择了错误的执行器实现?
英文:
I've submitted a job to Spring
ThreadPoolTaskExecutor
:
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
private Map<String,Runnable> runningTasks = new HashMap<>();
public String doSomeTask() {
Runnable job = new MyJob();
String id = RandomStringUtils.randomAlphanumeric(32);
taskExecutor.execute(job);
runningTasks.put(id, job);
return id;
}
Now I want to cancel some job. I have the runnable object, which has no interrupt()
method, because threads are managed by executor. But I can't find a method for cancelling a given job on the ThreadPoolTaskExecutor
.
Am I missing something obvious or I've taken the wrong executor implementation?
答案1
得分: 1
我甚至没有编译这个,但是想法非常类似于daniu和Savior在上面的评论中所提到的,
更改映射
//private Map<String,Runnable> runningTasks = new HashMap<>();
private Map<String,Future<?>> runningTasks = new HashMap<>();
使用submit来运行任务,
//taskExecutor.execute(job);
runningTasks.put(id, taskExecutor.submit(job));
然后当你需要取消任务时,只需从映射中获取它并执行以下操作
runningTasks.get(id).cancel(true);
英文:
I did not even compile this but the idea is very similar daniu and Savior's comment above,
change the map
//private Map<String,Runnable> runningTasks = new HashMap<>();
private Map<String,Future<?>> runningTasks = new HashMap<>();
use submit to run the task,
//taskExecutor.execute(job);
runningTasks.put(id, taskExecutor.submit(job));
then when you need to cancel a task, just get it from the map and
runningTasks.get(id).cancel(true);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论