2019-04-22 | UNLOCK

Spring Boot - Scheduling


调度是指执行特定时间段任务的过程,SpringBoot应用程序为任务调度提供了良好的支持。

Java Cron Expression

java Cron 表达式被用来配置CronTrigger(org.quartz.Trigger的子类)的实例,关于Java cron表达式你可以参考这个链接:
https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm
使用@EnableScheduling注解来开启应用程序的任务调度,这个注解应该被添加SpringBoot应用程序主类中,如下:

1
2
3
4
5
6
7
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

@Scheduled注解是用来触发特定时间段的任务,下面的案例将展示怎么在每天9:00am到9:59am期间每隔一分钟执行一次任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
@Scheduled(cron = "0 * 9 * * ?")
public void cronJobSch() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Java cron job expression:: " + strDate);
}
}

Fixed Rate

固定间隔任务计划是用来在指定的时间执行任务,它不会等待上一个任务的完成,值为毫秒为单位,下面的案例将展示从应用程序启动后每一秒中会执行一次任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
@Scheduled(fixedRate = 1000)
public void fixedRateSch() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Fixed Rate scheduler:: " + strDate);
}
}
``

## Fixed Delay
固定延迟任务计划是用来在特定的事件执行任务,它会等待前一个任务完成后,值为毫秒为单位,下面的案例将展示从应用程序启动后延迟三秒中,再每个一秒中执行一次任务
```java
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Scheduler {
@Scheduled(fixedDelay = 1000, initialDelay = 3000)
public void fixedDelaySch() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Fixed Delay scheduler:: " + strDate);
}
}

评论加载中

来发评论吧~
Powered By Valine
v1.5.2