如何取消 ThreadPoolTaskExecutor 任务

huangapple 未分类评论49阅读模式
英文:

How to cancel ThreadPoolTaskExecutor task

问题

我已经将作业提交给了SpringThreadPoolTaskExecutor

  1. @Autowired
  2. private ThreadPoolTaskExecutor taskExecutor;
  3. private Map<String, Runnable> runningTasks = new HashMap<>();
  4. public String doSomeTask() {
  5. Runnable job = new MyJob();
  6. String id = RandomStringUtils.randomAlphanumeric(32);
  7. taskExecutor.execute(job);
  8. runningTasks.put(id, job);
  9. return id;
  10. }

现在我想要取消一些作业。我有可运行的对象,但它没有interrupt()方法,因为线程是由执行器管理的。但我找不到在ThreadPoolTaskExecutor上取消给定作业的方法。

我是否忽略了一些明显的东西,或者我选择了错误的执行器实现?

英文:

I've submitted a job to Spring ThreadPoolTaskExecutor:

  1. @Autowired
  2. private ThreadPoolTaskExecutor taskExecutor;
  3. private Map&lt;String,Runnable&gt; runningTasks = new HashMap&lt;&gt;();
  4. public String doSomeTask() {
  5. Runnable job = new MyJob();
  6. String id = RandomStringUtils.randomAlphanumeric(32);
  7. taskExecutor.execute(job);
  8. runningTasks.put(id, job);
  9. return id;
  10. }

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在上面的评论中所提到的,

更改映射

  1. //private Map<String,Runnable> runningTasks = new HashMap<>();
  2. private Map<String,Future<?>> runningTasks = new HashMap<>();

使用submit来运行任务,

  1. //taskExecutor.execute(job);
  2. runningTasks.put(id, taskExecutor.submit(job));

然后当你需要取消任务时,只需从映射中获取它并执行以下操作

  1. 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

  1. //private Map&lt;String,Runnable&gt; runningTasks = new HashMap&lt;&gt;();
  2. private Map&lt;String,Future&lt;?&gt;&gt; runningTasks = new HashMap&lt;&gt;();

use submit to run the task,

  1. //taskExecutor.execute(job);
  2. runningTasks.put(id, taskExecutor.submit(job));

then when you need to cancel a task, just get it from the map and

  1. runningTasks.get(id).cancel(true);

huangapple
  • 本文由 发表于 2020年4月9日 22:30:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61123534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定