1

我在Executor这里定义了一个:

@Bean("asyncExecutor")
@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
    executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
    executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
    executor.setThreadNamePrefix("threadPoolExecutor-");
    executor.initialize();
    return executor;
}

我希望能够删除在队列中停留超过 X 分钟的任务(未处理 X 分钟)

有没有一种简单的方法可以做到这一点?我找不到任何东西。

4

1 回答 1

0

您可以将 ThreadPoolTask​​Executor 包装在一个自定义类中,该类将安排对任务状态的验证,如果未完成则将其取消。

public class CancellingExecutor implements Executor {

  private final ExecutorService delegate;
  private final ScheduledExecutorService monitoringExecutor;

  public CancellingExecutor(final ExecutorService delegate,
      final ScheduledExecutorService monitoringExecutor) {
    this.delegate = delegate;
    this.monitoringExecutor = monitoringExecutor;
  }

  @Override
  public void execute(final Runnable command) {
    Future<?> future = delegate.submit(command);
    monitoringExecutor.schedule(() -> {
      if (!future.isDone() && !future.isCancelled()) {
        future.cancel(false);
      }
    }, 1, TimeUnit.MINUTES);
  }
}

配置将如下所示:

@Bean("asyncExecutor")
@Override
public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(appConfigProperties.getThreadpoolCorePoolSize());
    executor.setMaxPoolSize(appConfigProperties.getThreadpoolMaxPoolSize());
    executor.setQueueCapacity(appConfigProperties.getThreadpoolQueueCapacity());
    executor.setThreadNamePrefix("threadPoolExecutor-");
    executor.initialize();
    ScheduledExecutorService monitoringExecutor = Executors.newScheduledThreadPool(1);
    return new CancellingExecutor(executor, monitoringExecutor);
}
于 2018-10-31T14:30:26.730 回答