本文主要是介绍SpringBoot (六) :SpringBoot定时器实现(简单入门),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
说在前面
定时任务一般会存在中大型企业级项目中,为了减少服务器、数据库的压力往往会采用时间段性的去完成某些业务逻辑。比较常见的就是金融服务系统推送回调,一般支付系统订单在没有收到成功的回调返回内容时会持续性的回调,这种回调一般都是定时任务来完成的。
SpringBoot为我们内置了定时任务,我们只需要一个注解(@Scheduled)就可以开启定时为我们所用了。
目录结构
代码实现
1、pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.fit</groupId><artifactId>SpringBootJob</artifactId><version>0.0.1-SNAPSHOT</version><!-- SpringBoot父类依赖引用 --><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.2.RELEASE</version></parent><!-- SpringBoot web 组件 --><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>
</project>
2、Scheduler文件
@Component
public class Scheduler { @Scheduled(cron="0 0/1 * * * ?") public void statusCheck() { System.out.println("每1分钟执行一次"); } @Scheduled(fixedRate=10000) public void testTasks() { System.out.println("每10秒执行一次。"); }
}
3、APP文件
@SpringBootApplication(scanBasePackages="com.fit.job")
@EnableScheduling
public class APP {public static void main(String[] args) {SpringApplication.run(APP.class, args);}
}
注:@SpringBootApplication(scanBasePackages=”com.fit.job”)中“scanBasePackages=”com.fit.job””表示扫描的包,如果是同包下可以不写,默认扫描当前目录
4、运行,输出结果
源码下载
这篇关于SpringBoot (六) :SpringBoot定时器实现(简单入门)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!