目录
1.定时任务的使用场景
在项目的开发过程中,我们经常会遇到类似这样的需求:需要定期执行某一项工作,或者按照特定计划执行某些工作
。这时我们就需要用到定时任务。
使用SpringBoot创建定时任务非常简单,目前主要有以下三种创建方式:
(1)基于注解(@Scheduled): 如果定时任务执行时间较短,并且比较单一,可以使用这个注解
(2)基于接口(SchedulingConfigurer)前者相信大家都很熟悉,但是实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
(3)开源的第三方框架: Quartz 或者 elastic-job
2.SpringBoot对定时任务的支持:
日常开发中,定时任务最常用的实现方式有如下两种:
- Spring-3.*版本之后,自带定时任务的实现(@Scheduled注解)
- SpringBoot-2.*版本之后,均实现了Quartz的自动配置
3.Spring自带定时任务的实现—@Scheduled注解
Spring自带定时任务的实现,是靠@Scheduled注解实现的。在SpringBoot项目中,我们想使该注解生效,还需要在类上加注解@EnableScheduling,开启对Spring定时任务的支持,测试源码如下:
4.代码实现
步骤流程如下:
(1)在spring boot的启动类上面添加 @EnableScheduling 注解
(2)创建一个类,在类前加@Configuration
注解。在类中需要定时执行的方法上方加上@Scheduled注解
(3)然后为Scheduled注解加上属性,启动项目,就可以了。
4.1创建springboot项目,添加web依赖
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
4.2 添加一个类,配置定时任务
创建一个类,在类前加@Configuration
注解。在类中需要定时执行的方法上方加上@Scheduled注解
,示例如下:
package com.example.scheduleddemo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 定时任务
* @author qzz
*/
@Configuration
public class ScheduleTask {
/**
* 添加定时任务:每隔5秒执行一次
*/
@Scheduled(cron = "0/5 * * * * ?")
private void configureTask(){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("执行静态定时任务时间:"+df.format(new Date()));
}
}
4.3 启动类上添加注解@EnableScheduling
package com.example.scheduleddemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 启动类
* @author qzz
*/
@SpringBootApplication
@EnableScheduling
public class ScheduledDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledDemoApplication.class, args);
}
}
4.3 启动项目,查看控制台输出
@Scheduled中的属性cron代表cron表达式,它是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,具体使用方法请自行百度。这里放出部分用法示例。除了cron属性,@Scheduled还有fixedDelay,fixedRate等属性可以使用。
// Cron表达式范例:
每隔5秒执行一次:*/5 * * * * ?
每隔1分钟执行一次:0 */1 * * * ?
每天23点执行一次:0 0 23 * * ?
每天凌晨1点执行一次:0 0 1 * * ?
每月1号凌晨1点执行一次:0 0 1 1 * ?
每月最后一天23点执行一次:0 0 23 L * ?
每周星期天凌晨1点实行一次:0 0 1 ? * L
在26分、29分、33分执行一次:0 26,29,33 * * *