依赖配置pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
动态配置ScheduleDynamicTask
@Configuration
@EnableScheduling
public class ScheduleDynamicTask implements SchedulingConfigurer, AsyncConfigurer {
// 日志工具
private final static Logger LOGGER = LoggerFactory.getLogger(ScheduleDynamicTask.class);
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
LOGGER.info("configureTasks start ... ");
// 设置并行定时任务线程池,最多三个任务并行
TaskScheduler taskScheduler = taskScheduler();
taskRegistrar.setTaskScheduler(taskScheduler);
//
String cron = "0/30 * * * * ?";
// 注册定时任务
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
LOGGER.info("Runnable : {}", System.currentTimeMillis());
}
}, new CronTrigger(cron));
LOGGER.info("configureTasks end ... ");
}
/** 定时任务多线程处理 */
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(3);
scheduler.setThreadNamePrefix("DynamicTask-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}
}
启动类Application
@SpringBootApplication
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class)
.bannerMode(Banner.Mode.OFF)
.build()
.run(args);
}
}
定时任务日志
输出示例:
2021-11-25 12:06:00.001 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813160001
2021-11-25 12:06:30.003 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813190003
2021-11-25 12:07:00.003 INFO 13828 --- [ DynamicTask-2] com.demo.ScheduleDynamicTask : Runnable : 1637813220003
2021-11-25 12:07:30.003 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813250003
2021-11-25 12:08:00.002 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813280002
2021-11-25 12:08:30.003 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813310003
2021-11-25 12:09:00.002 INFO 13828 --- [ DynamicTask-1] com.demo.ScheduleDynamicTask : Runnable : 1637813340002
2021-11-25 12:09:30.002 INFO 13828 --- [ DynamicTask-2] com.demo.ScheduleDynamicTask : Runnable : 1637813370002