Spring Boot 中使用 @Scheduled 注解创建定时任务

Spring Boot 默认已经实现了定时任务,只需要添加相应的注解即可完成

pom.xml 文件配置

pom.xml 不需要添加其他依赖,只需要加入 Spring Boot 依赖即可,这里我们添加一个 web 和 test 的依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
	</dependency>
</dependencies>

在启动类上面加上 @EnableScheduling 注解

在启动类上面加上 @EnableScheduling 注解即可开启定时任务

@EnableScheduling
@SpringBootApplication
public class SchedulingApplication {

	public static void main(String[] args) {
		SpringApplication.run(SchedulingApplication.class, args);
	}
}

编写定时任务

@Component
public class ScheduledTask {

    @Scheduled(initialDelay=1000, fixedDelay = 1000)
    public void task1() {
        System.out.println("延迟1000毫秒后执行,任务执行完1000毫秒之后执行!");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(fixedRate = 2000)
    public void task2() {
        System.out.println("延迟1000毫秒后执行,之后每2000毫秒执行一次!");
    }

}

除了这些还支持 cron 表达式

@Scheduled(cron = "*/2 * * * * ?")
public void task3() {
    System.out.println("每2秒执行一次!");
}

举几个例子

*/2 * * * * ?  表示每2秒执行一次!
0 0 2 1 * ? *  表示在每月的1日的凌晨2点调度任务 
0 15 10 ? * MON-FRI 表示周一到周五每天上午1015执行作业 
0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作

推荐一个 cron 表达式在线生成工具
http://cron.qqe2.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值