gpt4 book ai didi

java - 如果在某个固定时间后挂起,则停止 Spring Scheduled 执行

转载 作者:IT老高 更新时间:2023-10-28 13:56:48 26 4
gpt4 key购买 nike

我使用 Spring Framework 的 Scheduled 来安排我的作业使用 cron 每 5 分钟运行一次。但有时我的工作会无限等待外部资源,我不能在那里设置超时。我不能使用 fixedDelay 因为以前的进程有时会进入无限等待模式,我必须每 5 分钟刷新一次数据。

所以我在 Spring Framework 的 Scheduled 中寻找任何选项,以在 fixed-time 成功或不成功运行之后停止该进程/线程。

我发现下面的设置为我放入 @Configuration 类的 keepAliveTime 初始化了 120 秒的 ThreadPoolExecutor。谁能告诉我这会按我的预期工作吗?

@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
int coreThreads = 8;
int maxThreads = 20;
final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
coreThreads, maxThreads, 120L,
TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()
);
threadPoolExecutor.allowCoreThreadTimeOut(true);

return threadPoolExecutor;
}

最佳答案

我不确定这是否会按预期工作。实际上,keepAlive 是用于空闲线程的,我不知道您等待资源的线程是否处于空闲状态。此外,只有当线程数大于核心数时,除非您监视线程池,否则您无法真正知道它何时发生。

keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

你可以做的是:

public class MyTask {

private final long timeout;

public MyTask(long timeout) {
this.timeout = timeout;
}

@Scheduled(cron = "")
public void cronTask() {
Future<Object> result = doSomething();
result.get(timeout, TimeUnit.MILLISECONDS);
}

@Async
Future<Object> doSomething() {
//what i should do
//get ressources etc...
}
}

别忘了添加 @EnableAsync

通过实现 Callable 也可以在没有 @Async 的情况下做同样的事情。

编辑:请记住,它会等到超时,但运行任务的线程不会被中断。当 TimeoutException 发生时,您将需要调用 Future.cancel。并在任务中检查 isInterrupted() 以停止处理。如果您正在调用 api,请确保选中 isInterrupted()。

关于java - 如果在某个固定时间后挂起,则停止 Spring Scheduled 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39917757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com