最近在項(xiàng)目中遇到不少數(shù)據(jù)同步古涧,定時(shí)審核鹰溜、發(fā)布等需求,這時(shí)我們可以采用定時(shí)任務(wù)的方式去完成需求......
-
定時(shí)任務(wù)的實(shí)現(xiàn)方式
Timer方式
Timer:JDK自帶的java.util.Timer行贪,底層是使用一個(gè)單線來實(shí)現(xiàn)多個(gè)Timer任務(wù)處理的牵咙,所有任務(wù)都是由同一個(gè)線程來調(diào)度,所有任務(wù)都是串行執(zhí)行萄金,意味著同一時(shí)間只能有一個(gè)任務(wù)得到執(zhí)行蟀悦,而前一個(gè)任務(wù)的延遲或者異常會(huì)影響到之后的任務(wù)
package com.ooliuyue.springboottask.task;
import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;
/**
* 基于Timer實(shí)現(xiàn)的定時(shí)調(diào)度,不推薦
* @Auther: ly
* @Date: 2019/1/2 15:53
*/
public class TimerDemo{
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("執(zhí)行任務(wù)" + LocalDateTime.now());
}
};
Timer timer = new Timer();
//在3秒后執(zhí)行timerTask中的run方法,后面每5秒跑一次
timer.schedule(timerTask,3000,5000);
}
}
基于 ScheduledExecutorService
ScheduledExecutorService: JDK1.5新增的氧敢,位于java.util.concurrent包中日戈;是基于線程池設(shè)計(jì)的定時(shí)任務(wù)類,每個(gè)調(diào)度任務(wù)都會(huì)被分配到線程池中孙乖,并發(fā)執(zhí)行浙炼,互不影響。
package com.ooliuyue.springboottask.task;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @Auther: ly
* @Date: 2019/1/2 16:22
*/
public class ScheduledExecutorServiceDemo {
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10);
scheduledExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
//3秒后每秒執(zhí)行一次
},3,3, TimeUnit.SECONDS);
}
}
Spring Task
Spring Task: Spring3.0 以后新增了task唯袄,一個(gè)輕量級(jí)的Quartz弯屈,功能夠用,用法簡(jiǎn)單恋拷。
接下來講述如何在SpringBoot中使用季俩。
-
導(dǎo)入依賴
在 pom.xml 中添加 spring-boot-starter-web 依賴即可,它包含了spring-context梅掠,定時(shí)任務(wù)相關(guān)的就屬于這個(gè)JAR下的org.springframework.scheduling包中
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
-
定時(shí)任務(wù)
package com.ooliuyue.springboottask.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* @Auther: ly
* @Date: 2019/1/2 17:12
*/
@Component
public class SpringTaskDemo {
private static final Logger log = LoggerFactory.getLogger(SpringTaskDemo.class);
@Async //代表該任務(wù)可以進(jìn)行異步工作酌住,由原本的串行改為并行
@Scheduled(cron = "0/1 * * * * *") //定時(shí)任務(wù)的核心
public void scheduled1() throws InterruptedException {
Thread.sleep(3000);
log.info("scheduled1 每1秒執(zhí)行一次 :{}", LocalDateTime.now());
}
}
-
主函數(shù)
package com.ooliuyue.springboottask;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
@EnableAsync 注解表示開啟@Async注解的解析;作用就是將串行化的任務(wù)給并行化了阎抒。
(@Scheduled(cron = "0/1 * * * * *")假設(shè)第一次工作時(shí)間為2018-05-29 17:30:55酪我,工作周期為3秒;
如果不加@Async那么下一次工作時(shí)間就是2018-05-29 17:30:59且叁;
如果加了@Async 下一次工作時(shí)間就是2018-05-29 17:30:56)
*/
@EnableAsync
/**
@EnableScheduling 注解表示開啟對(duì)@Scheduled注解的解析都哭;
同時(shí)new ThreadPoolTaskScheduler()也是相當(dāng)?shù)年P(guān)鍵,
通過閱讀過源碼可以發(fā)現(xiàn)默認(rèn)情況下的 private volatile int poolSize = 1;
這就導(dǎo)致了多個(gè)任務(wù)的情況下容易出現(xiàn)競(jìng)爭(zhēng)情況(多個(gè)任務(wù)的情況下,如果第一個(gè)任務(wù)沒執(zhí)行完畢欺矫,后續(xù)的任務(wù)將會(huì)進(jìn)入等待狀態(tài))
*/
@EnableScheduling //開啟對(duì)@Scheduled注解的解析
@SpringBootApplication
public class SpringbootTaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTaskApplication.class, args);
}
/**
* 默認(rèn)情況下 TaskScheduler 的 poolSize = 1
* @return 線程池
*/
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
return taskScheduler;
}
}
-
測(cè)試
完成準(zhǔn)備事項(xiàng)后纱新,啟動(dòng)SpringbootTaskApplication ,觀察日志信息如下
2019-01-02 18:05:40.043 INFO 9920 --- [cTaskExecutor-1] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:40.043
2019-01-02 18:05:41.002 INFO 9920 --- [cTaskExecutor-2] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:41.002
2019-01-02 18:05:42.001 INFO 9920 --- [cTaskExecutor-3] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:42.001
2019-01-02 18:05:43.001 INFO 9920 --- [cTaskExecutor-4] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:43.001
2019-01-02 18:05:44.001 INFO 9920 --- [cTaskExecutor-5] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:44.001
2019-01-02 18:05:45.001 INFO 9920 --- [cTaskExecutor-6] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:45.001
2019-01-02 18:05:46.001 INFO 9920 --- [cTaskExecutor-7] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:46.001
2019-01-02 18:05:47.002 INFO 9920 --- [cTaskExecutor-8] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:47.002
2019-01-02 18:05:48.001 INFO 9920 --- [cTaskExecutor-9] c.o.springboottask.task.SpringTaskDemo : scheduled1 每1秒執(zhí)行一次 :2019-01-02T18:05:48.001