java - 如何配置 spring 来执行重叠的 fixedRate 任务?

标签 java multithreading spring

我正在尝试使用 java spring 中的 @Scheduled 注释以固定速率执行任务。但是,如果任务慢于速率,默认情况下 spring 似乎不会以固定速率执行 fixedRate 任务。是否有一些设置可以添加到我的 spring 配置中以更改此行为?

示例:

@Service
public class MyTask{
    @Scheduled(fixedRate = 1000)
    public void doIt(){
        // this sometimes takes >1000ms, in which case the next execution is late
        ...
    }
}

我有一个变通办法,但似乎不太理想。基本上,我只是用线程池替换默认的单线程执行器,然后我有一个计划的方法调用异步方法,因为 @Async 注释允许并发执行:

@Service
public class MyTask{
    @Async
    public void doIt(){
        // this sometimes takes >1000ms, but the next execution is on time
        ...
    }
}

@Service
public class MyTaskScheduler{
    ...
    @Scheduled(fixedRate = 1000)
    public void doIt(){
        myTask.doIt();
    }
}

@Configuration
@EnableScheduling
@EnableAsync
public class MySpringJavaConfig{
    @Bean(destroyMethod = "shutdown")
    public Executor taskScheduler() {
        return Executors.newScheduledThreadPool(5);
    }
}

我的真实场景的无聊细节:在我的生产代码中,我有一个任务需要 10 毫秒到 10 分钟,具体取决于当前的工作量。理想情况下,我想每 1000 毫秒从池中捕获一个新线程,以便并发线程的数量随着工作负载的增加而增加。显然,我对线程(以及其他控件)有一个上限,以防止事情失控。

最佳答案

TaskScheduler API(支持一些 Spring Scheduling 行为)似乎被定义为防止您请求的行为

Schedule the given Runnable, invoking it at the specified execution time and subsequently with the given period.

Parameters

  • period the interval between successive executions of the task (in milliseconds)

subsequentlysuccessive 似乎表明下一次执行只会在当前执行完成后发生。

此外,ScheduledExecutorService#scheduleAtFixedRate(..) (内置的 TaskScheduler 实现使用)也说

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

因此还有另一层实现可以阻止您想要的行为。

一种可能的解决方案是定义并提供您自己的 TaskScheduler 并发运行任务,因为 API 似乎不是围绕它构建的,因此我不推荐这种解决方案。查看@EnableSchedulingSchedulingConfigurer了解如何注册 TaskScheduler

关于java - 如何配置 spring 来执行重叠的 fixedRate 任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30313277/

相关文章:

java - 从 SimpleJdbcTemplate 查询返回的大列表

linux - 是否可以在线程之间共享一个寄存器?

python - Python 中的多线程可打开数千个 url 并更快地处理它们

java - 事务不回滚

java - 用户连接的全局架构存在

Spring Boot : serving static content with war packagin

java - Zookeeper 多领导选举问题

java - Android Studio 无法创建新项目

java - Websphere 不信任的证书

multithreading - 使用performSelectorInBackground在单独的线程中处理代码时更新cocoa接口(interface)