spring boot定时任务(Scheduled Tasks)

spring boot中使用定时:

方式1:

新建一个java类,添加注解@Configuration@EnableScheduling,开启调度任务。在类中新建一个定时的方法添加注解@Scheduled ,表明该方法是一个调度任务。cron表达式配置定时执行的规则

实例:

@Configuration

@EnableScheduling

public classSpringBootScheduledController {

/**

*每20秒执行一次

*/

@Scheduled(cron="0/20 * * * * ?")

public voidmethodScheduling(){

System.out.println("methodScheduling定时任务启动了");

}

}

方式2:

在启动类上添加注解@EnableScheduling,开启调度任务。创建一个任务类添加注解@Component,类中方法添加注解@Scheduled,表明该方法是一个调度任务。

示例:

启动类

@SpringBootApplication

@EnableScheduling

public classSpringBootRestApplication {

public static voidmain(String[] args) {

SpringApplication.run(SpringBootRestApplication.class,args);

}

}

任务类

@Component

public classSpringBootScheduledController {

/**

*每20秒执行一次

*/

@Scheduled(cron="0/20 * * * * ?")

public voidmethodScheduling(){

System.out.println("methodScheduling定时任务启动了");

}

}

说明:

@Scheduled(cron="0/10 * * * * ?")//通过cron表达式定义执行规则, 每隔十秒执行1次

@Scheduled(fixedRate=1000)//上次开始执行时间点之后1秒再执行

@Scheduled(fixedDelay=1000)//上次执行完毕时间点之后1秒再执行

@Scheduled(initialDelay=1000,fixedRate=1000)//第一次延迟1秒后执行,之后按fixedRate的规则每1秒执行1次

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容