欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)

程序员文章站 2022-07-14 18:53:40
...

一、使用场景

定时任务在开发中还是比较常见的,比如:定时发送邮件,定时发送信息,定时更新资源,定时更新数据等等…

二、准备工作

在Spring Boot程序中不需要引入其他Maven依赖
(因为spring-boot-starter-web传递依赖了spring-context模块)

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

三、开始搭建配置

  • 配置启动项
package com.wang.test.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling//启动定时任务
public class DemoApplication {

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

}

  • cron表达式

关于cron表达式,小编这里不做过多介绍,这里是cron生成器,大家可以参考
https://www.matools.com/cron/

  • 定时任务方法
package com.wang.test.demo.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component//加载到容器中,可以被发现启动
public class TaskTest {

	//cron表达式,来控制定时执行时间,这里是每5秒执行一次本方法,业务逻辑可以进行在此方法内进行书写
    @Scheduled(cron = "0/5 * * * * ?")
    public void printTimeOne(){

        System.out.println("任务一:时间为-->"+System.currentTimeMillis());
    }

    @Scheduled(cron = "0/6 * * * * ?")
    public void printTimeTwo(){

        System.out.println("任务二:时间为-->"+System.currentTimeMillis());

    }

}

四、结果展示

SpringBoot整合定时任务----Scheduled注解实现(一个注解全解决)

五、总结

这样就完整了SpringBoot整合定时任务了,一个注解全搞定,非常简洁好动.