spring Schedule多定时任务动态实现

运用的是spring自带的SchedulingConfigurer,但是这种方式适用于单体项目,如果是分布式项目还需要用quartz来实现
首先新建一个springboot项目
1、在启动类上加注解@EnableScheduling
2、创建自定义ScheduleConfig.java类

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
     

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
     
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
     
        // 设置并行线程数1个,可以设置多个并行线程
        return Executors.newScheduledThreadPool(1);
    }
}

3、创建任务类task1.java、task2.java

@Component
public class task1 {
     
    private static final Logger logger = LoggerFactory.getLogger(task1.class);
    @Scheduled(cron = "0/1 * * * * ?")
    public void task1(){
     
        logger.info("task111111");
        try {
     
            Thread.sleep(3000);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        doService();
    }
    public void doService(){
     

        logger.info("task1------service");
    }
}
@Component
public class task2 {
     
    private static final Logger logger = LoggerFactory.getLogger(task2.class);
    //定时任务执间隔时间
    @Scheduled(cron = "0/1 * * * * ?")
    public void task2(){
     
        logger.info("task222222222222");
        doService();
    }
    public void doService(){
     
        try {
     
            Thread.sleep(3000);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        logger.info("task2------service");
    }
}

运行springboot 项目,系统会在后台打印日志如图:
spring Schedule多定时任务动态实现_第1张图片

你可能感兴趣的:(java,spring,boot,多线程)