Spring Boot 內置定時
pom 包配置
pom 包⾥⾯只需要引⼊ Spring Boot Starter 包即可,Spring Boot Starter 包中已經內置了定時的⽅法。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
啓動類開啓定時
@Spring BootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
創建定時任務實現類
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm
:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("現在時間:" + dateFormat.format(new Date()));
}
}
this is scheduler task runing 0
現在時間:09:44:17
this is scheduler task runing 1
現在時間:09:44:23
this is scheduler task runing 2
現在時間:09:44:29
this is scheduler task runing 3
現在時間:09:44:35
fifixedRate 說明
- @Scheduled(fifixedRate = 6000):上⼀次開始執⾏時間點之後 6 秒再執⾏。
- @Scheduled(fifixedDelay = 6000):上⼀次執⾏完畢時間點之後 6 秒再執⾏。
- @Scheduled(initialDelay=1000, fifixedRate=6000):第⼀次延遲 1 秒後執⾏,之後按 fifixedRate 的規則 每 6 秒執⾏⼀次。
cron 說明
- 第⼀位,表示秒,取值 0 ~ 59;
- 第⼆位,表示分,取值 0 ~ 59;
- 第三位,表示⼩時,取值 0 ~ 23;
- 第四位,⽇期天/⽇,取值 1 ~ 31;
- 第五位,⽇期⽉份,取值 1~12;
- 第六位,星期,取值 1 ~ 7,星期⼀,星期⼆...,注,不是第 1 周、第 2 周的意思,另外,1 表示星期 天,2 表示星期⼀;
- 第七位,年份,可以留空,取值 1970 ~ 2099。
- (*)星號,可以理解爲每的意思,每秒、每分、每天、每⽉、每年...。
- (?)問號,問號只能出現在⽇期和星期這兩個位置,表示這個位置的值不確定,每天 3 點執⾏,因此 第六位星期的位置,是不需要關注的,就是不確定的值;同時,⽇期和星期是兩個相互排斥的元素,通 過問號來表明不指定值,⽐如 1 ⽉ 10 ⽇是星期⼀,如果在星期的位置另指定星期⼆,就前後衝突⽭盾 了。
- (-)減號,表達⼀個範圍,如在⼩時字段中使⽤“10 ~ 12”,則表示從 10 到 12 點,即 10、11、12。
- (,)逗號,表達⼀個列表值,如在星期字段中使⽤“1、2、4”,則表示星期⼀、星期⼆、星期四。
- (/)斜槓,如 x/y,x 是開始值,y 是步⻓,⽐如在第⼀位(秒),0/15 就是從 0 秒開始,每隔 15 秒執 ⾏⼀次,最後就是 0、15、30、45、60,另 */y,等同於 0/y。
- 0 0 3 * * ? :每天 3 點執⾏;
- 0 5 3 * * ?:每天 3 點 5 分執⾏;
- 0 5 3 ? * *:每天 3 點 5 分執⾏,與上⾯作⽤相同;
- 0 5/10 3 * * ?:每天 3 點的 5 分、15 分、25 分、35 分、45 分、55 分這⼏個時間點執⾏;
- 0 10 3 ? * 1:每週星期天,3 點 10 分執⾏,注,1 表示星期天;
- 0 10 3 ? * 1#3:每個⽉的第三個星期,星期天執⾏,# 號只能出現在星期的位置。
Quartz
Quartz 介紹
Quartz 的優點:
- 豐富的 Job 操作 API;
- ⽀持多種配置;
- Spring Boot ⽆縫集成;
- ⽀持持久化;
- ⽀持集羣;
- Quartz 還⽀持開源,是⼀個功能豐富的開源作業調度庫,可以集成到⼏乎任何 Java 應⽤程序中。
Quartz 體系結構
Spring Boot 和 Quartz
配置內容
配置 pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
簡單示例
public class SampleJob extends QuartzJobBean {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
System.out.println(String.format("Hello %s!", this.name));
}
}
@Configuration
public class SampleScheduler {
@Bean
public JobDetail sampleJobDetail() {
return JobBuilder.newJob(SampleJob.class).withIdentity("sampleJob")
.usingJobData("name", "World").storeDurably().build();
}
@Bean
public Trigger sampleJobTrigger() {
SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedu
le()
.withIntervalInSeconds(2).repeatForever();
return TriggerBuilder.newTrigger().forJob(sampleJobDetail())
.withIdentity("sampleTrigger").withSchedule(scheduleBuilder).build
();
}
}
- JobBuilder ⽆構造函數,只能通過 JobBuilder 的靜態⽅法 newJob(Class<? extends Job> jobClass)⽣ 成 JobBuilder 實例。
- withIdentity ⽅法可以傳⼊兩個參數 withIdentity(String name,String group) 來定義 TriggerKey,也可以 不設置,像上⽂示例中會⾃動⽣成⼀個獨⼀⽆⼆的 TriggerKey ⽤來區分不同的 Trigger。
Hello World!
Hello World!
Hello World!
...
CronSchedule 示例
public class ScheduledJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException
{
System.out.println("schedule job1 is running ...");
}
}
private void scheduleJob1(Scheduler scheduler) throws SchedulerException{
JobDetail jobDetail = JobBuilder.newJob(ScheduledJob.class) .withIdentity("job
1", "group1").build();
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/6 *
* * * ?");
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1",
"group1") .withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail,cronTrigger);
}
- CronScheduleBuilder.cronSchedule("0/6 * * * * ?"),按照 cron 表達式設置定時任務的執⾏週期。
public void scheduleJobs() throws SchedulerException {
Scheduler scheduler = schedulerFactoryBean.getScheduler();
scheduleJob1(scheduler);
scheduleJob2(scheduler);
}
何時觸發定時任務
@Component
public class MyStartupRunner implements CommandLineRunner {
@Autowired
public CronSchedulerJob scheduleJobs;
@Override
public void run(String... args) throws Exception {
scheduleJobs.scheduleJobs();
System.out.println(">>>>>>>>>>>>>>>定時任務開始執⾏<<<<<<<<<<<<<");
}
}
@Configuration
@EnableScheduling
@Component
public class SchedulerListener {
@Autowired
public CronSchedulerJob scheduleJobs;
@Scheduled(cron="0 30 11 25 11 ?")
public void schedule() throws SchedulerException {
scheduleJobs.scheduleJobs();
}
}
Hello World!
Hello World!
Hello World!
schedule job1 is running ...
Hello World!
Hello World!
Hello World!
schedule job1 is running ...
schedule job2 is running ...
...