Api说明
- fixedDelay
上一次执行完毕时间点之后多长时间再执行。如:
@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
- fixedRate
上一次开始执行时间点之后多长时间再执行。如:
@Scheduled(fixedRate = 5000) //上一次开始执行时间点之后5秒再执行
- initialDelay
第一次延迟多长时间后再执行。如:
@Scheduled(initialDelay=1000, fixedRate=5000) //第一次延迟1秒后执行, 之后按fixedRate的规则每5秒执行一次
- cron
该参数接收一个cron表达式,cron表达式是一个字符串,字符串以5或6个空格隔开,分开共6或7个域,每一个域代表一个含义。
cron在线生成器
https://www.bejson.com/othertools/cron/
具体应用
package com.beiyou.Schedule;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ScheduledDemo {
//每五秒执行一次
@Scheduled(fixedRate = 5000)
public void fixedRate(){
log.info("fixedRate开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
ThreadUtil.safeSleep(8000);
log.info("fixedRate结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
}
//上次执行完成之后5秒再执行
@Scheduled(fixedDelay = 5000)
public void fixedDelay(){
log.info("fixedDelay开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
ThreadUtil.safeSleep(8000);
log.info("fixedDelay结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
}
//第一次执行的时候延迟initalDelay秒,然后每次完成之后,fixedDeLay在执行
@Scheduled(initialDelay = 2000,fixedDelay = 3000)
public void initialDelay(){
log.info("initialDelay开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
ThreadUtil.safeSleep(8000);
log.info("initialDelay结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
}
//通过core表达式执行任务
@Scheduled(cron = "0/5 * * * * ?")
public void cron(){
log.info(" cron开始执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
ThreadUtil.safeSleep(8000);
log.info(" cron结束执行时间{},线程名字 {}", DateUtil.now(),Thread.currentThread().getName());
}
}
启动类加入@EnableScheduling
package com.beiyou;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}



