springboot 定时任务@Scheduled实现解析
这篇文章主要介绍了springboot定时任务@Scheduled实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、pom.xml中导入必要的依赖:
org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat
2、写一个springboot的启动类:
importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan(basePackages={"com.xwj.tasks"})
@EnableScheduling//开启定时任务
@EnableAutoConfiguration
publicclassApp{
publicstaticvoidmain(String[]args){
SpringApplication.run(App.class,args);
}
}
注意这里一定要加上@EnableScheduling注解,用于开启定时任务
3、开始写定时任务:
importorg.springframework.scheduling.annotation.Scheduled;
importorg.springframework.stereotype.Component;
@Component
publicclassScheduleTask{
@Scheduled(fixedRate=1000)
//@Scheduled(cron="023-2518**?")
publicvoidtestSchedule(){
System.out.println("定时任务:"+System.currentTimeMillis());
}
}
解释:
@Scheduled注解:
1、fixedRate以固定速率执行。以上表示每隔1秒执行一次
2、fixedDelay以上一个任务开始时间为基准,从上一任务开始执行后再次调用
3、cron表达式。可以实现定时调用。
在使用的过程中,楼主觉得,如果只有一个定时任务,fixedRate与fixedDelay的效果是一样一样的
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。