定时任务一般会存在中大型企业级项目中,为了减少服务器、数据库的压力往往会采用时间段性的去完成某些业务逻辑。比较常见的就是金融服务系统推送回调,一般支付系统订单在没有收到成功的回调返回内容时会持续性的回调,这种回调一般都是定时任务来完成的。还有就是报表的生成,我们一般会在客户访问量过小的时候来完成这个操作,那往往都是在凌晨。这时我们也可以采用定时任务来完成逻辑。SpringBoot为我们内置了定时任务,我们只需要一个注解就可以开启定时为我们所用了。
在开发中,定时任务是常见的功能,在spring boot 下开发定时任务其实很简单,具体代码如下:
1、配置依赖包pom.xml
由于默认的maven仓库经常访问不了,这里采用了阿里云的maven仓库镜像。
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://.example;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class SpringBootScheduledApplication { public static void main(String[] args) { SpringApplication.run(SpringBootScheduledApplication.class, args); }}4、输出结果
20:16:27init : 20:16:28init : 20:16:30init : 20:16:32init : 20:16:34init : 20:16:3620:16:37init : 20:16:38init : 20:16:40init : 20:16:42init : 20:16:44init : 20:16:4620:16:47init : 20:16:48current time : 20:16:50init : 20:16:50init : 20:16:52init : 20:16:54总结
以上就是本文关于Springboot通过Scheduled实现定时任务代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:
Spring boot跨域设置实例详解
快速了解Spring Boot
浅谈Springboot之于Spring的优势
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!