定時(shí)任務(wù)在我們開發(fā)中是廣泛存在的,定時(shí)任務(wù)在初期我一般是直接利用多線程來實(shí)現(xiàn)突硝,對(duì)于新手來說比較的復(fù)雜也不容易理解设拟。自從接觸到 Quartz之后,就感覺復(fù)雜的東西簡(jiǎn)單化是多么的重要浴井。
Quartz簡(jiǎn)介
Quartz是OpenSymphony開源組織在Job scheduling領(lǐng)域又一個(gè)開源項(xiàng)目晒骇,它可以與J2EE與J2SE應(yīng)用程序相結(jié)合也可以單獨(dú)使用。Quartz可以用來創(chuàng)建簡(jiǎn)單或?yàn)檫\(yùn)行十個(gè)磺浙,百個(gè)洪囤,甚至是好幾萬(wàn)個(gè)Jobs這樣復(fù)雜的程序。Jobs可以做成標(biāo)準(zhǔn)的Java組件或 EJBs撕氧。Quartz的最新版本為Quartz 2.3.0瘤缩。(百度抄來的)
廢話不多說直接上手
1、搭建SpringBoot開發(fā)環(huán)境
2伦泥、在pom.xml中加入依賴
<!--spring boot集成quartz-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.2.3</version>
</dependency>
3剥啤、編寫application類(在類名上注解@EnableScheduling)
package com.alery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
//掃描指定的包
//@SpringBootApplication(scanBasePackages={"com.lx.controller","com.lx.interceptor","com.lx.service","com.lx.dao"})
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
注意:Application文件的位置
Application
4、編寫任務(wù)類(在任務(wù)方法上注解@Scheduled(cron = "*/2 * * * * ?"))
package com.alery.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class JobService {
int i=0;
//cron = "0/3 40 11 * * ?" 每天11:40觸發(fā)不脯,沒三秒執(zhí)行一次
@Scheduled(cron = "*/2 * * * * ?")
public void printTime() {
System.out.println("current time :"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
System.out.println("i="+(i++));
}
@Scheduled(cron = "*/10 * * * * ?")
public void printTime2() {
System.err.println("current time :"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
System.err.println("現(xiàn)在向數(shù)據(jù)庫(kù)導(dǎo)入100條數(shù)據(jù)");
}
}
cron表達(dá)式可以自行百度
5府怯、結(jié)果
執(zhí)行結(jié)果