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、运行,输出结果
这里写图片描述

源码下载

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值