SpringBoot添加多个定时任务

1、创建好springboot项目,不需要任何的其他包

2、在启动类上添加注解@EnableScheduling即可开启定时任务

@SpringBootApplication
@EnableScheduling
public class WebsitemonitoringApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebsitemonitoringApplication.class, args);
    }

}

3、创建定时任务,在类上添加注解@Component,方法上添加注解@Scheduled(cron="*/6 * * * * ?")

其中cron="*/6 * * * * ?"或者fixedRate = 6000都表示6秒执行一次

启动项目后,添加注解的@Scheduled(cron="*/6 * * * * ?")的方法会自动定时,cron的定时确定算法详见http://cron.qqe2.com/

定时代码

@Component
public class SchedulerTaskWhhlyt {

    @Scheduled(cron="*/9 * * * * ?")
    private void testing1(){
        // 定时任务1
    }
@Component
public class SchedulerTaskWhhlyt {

    @Scheduled(cron="*/9 * * * * ?")
    private void testing2(){
        // 定时任务2
    }

fixedRate 说明

@Scheduled(fixedRate = 6000) :上一次开始执行时间点之后6秒再执行
@Scheduled(fixedDelay = 6000) :上一次执行完毕时间点之后6秒再执行
@Scheduled(initialDelay=1000, fixedRate=6000) :第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次

猜你喜欢

转载自blog.csdn.net/weixin_41996632/article/details/88645362
今日推荐