我正在 Spring Boot 中创建一个应用程序,它需要实现一个复杂的批处理任务,例如,有一个包含所有作业的表,如下所示,
BATCH_JOBS(id, job, cron_expression)
row count may be huge but job execution time will be very low.
有什么办法可以实现这个处理吗?假设我每 5 分钟或 10 分钟就有一个 @Schedule 方法,当它的运行将根据 cron_expression 列决定需要执行哪个作业并将它们拆分到线程中时。线程将独立运行执行作业列并将结果保存到日志中。提前致谢。
最佳答案
您可以为此使用@EnableAsync
和@Async
注释。
例如
@Configuration
@EnableScheduling
public class SpringConfig {
...
}
然后
public class ScheduledFixedRateExample {
@Async
@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleFixedRateTaskAsync() throws InterruptedException {
System.out.println(
"Fixed rate task async - " + System.currentTimeMillis() / 1000);
Thread.sleep(2000);
}
}
信用:https://www.baeldung.com/spring-scheduled-tasks
您可以通过附加配置相应地增加线程池大小:
package com.example.schedulerdemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
threadPoolTaskScheduler.setThreadNamePrefix("my-scheduled-task-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
信用:https://www.callicoder.com/spring-boot-task-scheduling-with-scheduled-annotation/
将 @Async
与 cron 作业结合使用的更多示例:
https://javadigest.wordpress.com/2012/06/01/spring-scheduling-using-annotations/
关于java - 如何在 Spring Boot 中动态运行 cron,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60493609/