程序中若需要在某个时间循环执行某项任务,就可以使用@Scheduled
定时器在springboot中简单的实现,话不多说,一个注解搞定。
一、实现定时任务
先开启定时任务
@SpringBootApplication
@EnableScheduling //开启定时任务
public class Demo4Application {
public static void main(String[] args) {
SpringApplication.run(Demo4Application.class, args);
}
}
使用 @Scheduled注解
@Controller
@RequestMapping("/get")
public class test {
int i=0;
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
public void sout(){
System.out.println("第"+(i++)+"次执行");
}
}
二、注解的解释
@Scheduled注解各大参数的作用
具体参数有如下:cron
、zone
、fixedDelay
、fixedDelayString
、fixedRate
、fixedRateString
、initialDelay
、initialDelayString
看源码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.scheduling.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.TimeUnit;
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
String CRON_DISABLED = "-";
String cron() default "";
String zone() default "";
long fixedDelay() default -1L;
String fixedDelayString() default "";
long fixedRate() default -1L;
String fixedRateString() default "";
long initialDelay() default -1L;
String initialDelayString() default "";
TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}
1、cron相关参数意义
一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。
按顺序依次为
秒(0~59) 例如0/5表示每5秒
分钟(0~59)
小时(0~23)
天(月)(0~31,但是你需要考虑你月的天数)
月(0~11)
天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
年份(1970-2099)——@Scheduled是不支持的,spring quartz支持
2、
zone
时区,接收一个 java.util.TimeZone#ID
。cron
表达式会基于该时区解析。默认是一个空字符串,即取服务器所在地的时区。比如我们一般使用的时区Asia/Shanghai。该字段我们一般留空。
3、fixedDelay
、fixedDelayString
这两个参数意思是相同的,都是表示:上一次执行完毕时间点之后多长时间再执行,区别是:后者支持占位符。
4、fixedRate、fixedRateString
这两个参数意思是相同的,都是表示:上一次开始执行时间点之后多长时间再执行,区别是:后者支持占位符。
5、initialDelay、initialDelayString
这两个参数意思是相同的,都是表示:第一次延迟多长时间后再执行,区别是:后者支持占位符。