如何取消 ThreadPoolTaskExecutor 任务

huangapple go评论106阅读模式
英文:

How to cancel ThreadPoolTaskExecutor task

问题

我已经将作业提交给了SpringThreadPoolTaskExecutor

@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&lt;String,Runnable&gt; runningTasks = new HashMap&lt;&gt;();
  
  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&lt;String,Runnable&gt; runningTasks = new HashMap&lt;&gt;();
private Map&lt;String,Future&lt;?&gt;&gt; runningTasks = new HashMap&lt;&gt;();

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);

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

发表评论

匿名网友

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

确定