1.Quartz的介紹
Quartz是Job scheduling(作業調度)領域的一個開源項目,Quartz既可以單獨使用也可以跟spring框架整合使用,在實際開發中一般會使用后者。使用Quartz可以開發一個或者多個定時任務,每個定時任務可以單獨指定執行的時間,例如每隔1小時執行一次、每個月第一天上午10點執行一次、每個月最后一天下午5點執行一次等。
官網:http://www.quartz-scheduler.org/
2.Quartz的使用步驟
1.
webapp骨架
2.修改pom.xml文件
引入需要的三方庫
3.自定義一個任務類
調用任務類,普通類普通方法
4.增加spring-jobs.xml文件
配置任務對象、調度對象,調度工廠
5.修改web.xml文件
容器啟動,加載spring配置文件
3.Quartz的使用演示
本案例基於Quartz和spring整合的方式使用。具體步驟:
(1)創建maven子模塊工程health-jobs,骨架webapp
(2)修改pom.xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <artifactId>itcast_health</artifactId> 7 <groupId>com.itheima.health</groupId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 12 <artifactId>health-jobs</artifactId> 13 <packaging>war</packaging> 14 15 <name>health-jobs</name> 16 17 <properties> 18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 19 <maven.compiler.source>1.7</maven.compiler.source> 20 <maven.compiler.target>1.7</maven.compiler.target> 21 </properties> 22 <dependencies> 23 24 <dependency> 25 <groupId>com.itheima.health</groupId> 26 <artifactId>health_common</artifactId> 27 <version>1.0-SNAPSHOT</version> 28 </dependency> 29 <dependency> 30 <groupId>org.springframework</groupId> 31 <artifactId>spring-webmvc</artifactId> 32 </dependency> 33 <dependency> 34 <groupId>org.springframework</groupId> 35 <artifactId>spring-tx</artifactId> 36 </dependency> 37 <dependency> 38 <groupId>org.quartz-scheduler</groupId> 39 <artifactId>quartz</artifactId> 40 </dependency> 41 <dependency> 42 <groupId>org.quartz-scheduler</groupId> 43 <artifactId>quartz-jobs</artifactId> 44 </dependency> 45 <dependency> 46 <groupId>redis.clients</groupId> 47 <artifactId>jedis</artifactId> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-context-support</artifactId> 52 </dependency> 53 <dependency> 54 <groupId>com.qiniu</groupId> 55 <artifactId>qiniu-java-sdk</artifactId> 56 </dependency> 57 </dependencies> 58 <build> 59 <finalName>health-jobs</finalName> 60 <plugins> 61 <plugin> 62 <groupId>org.apache.tomcat.maven</groupId> 63 <artifactId>tomcat7-maven-plugin</artifactId> 64 <configuration> 65 <path>/</path> 66 <port>9003</port> 67 </configuration> 68 </plugin> 69 </plugins> 70 </build> 71 </project>
main下創建java目錄 (刷新maven工程),然后創建com.itheima.health.jobs包,然后新建一個任務調度類ClearImageJob,任務內容暫時做普通打印即可。
/**
* 定時任務:在這里定義你想要完成的功能
*public class ClearImageJob {
/**
* 定義清理圖片的任務
*/
public void clearImageJob(){
System.out.println("clearImageJob......");
}
}
(4)創建配置文件spring-jobs.xml,配置自定義Job、任務描述、觸發器、調度工廠等
-
自動掃包
-
注冊任務對象
-
注冊JobDetail
-
定義觸發器
-
定義調度工廠
在main下創建resources目錄,刷新maven后,在目錄下創建spring-jobs.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context.xsd"> 9 10 <!--自動掃包,后續注入jedis到任務調度類--> 11 <context:component-scan base-package="com.itheima.health"/> 12 <!--注冊一個定義任務對象--> 13 <bean id = "clearImgJob" class="com.itheima.health.jobs.ClearImageJob"/> 14 <!-- 注冊JobDetail,作用是負責通過反射調用指定的Job --> 15 <bean id="clearImgJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 16 <!--注入對象--> 17 <property name="targetObject" ref="clearImgJob"/> 18 <!--注入方法--> 19 <property name="targetMethod" value="clearImageJob"/> 20 </bean> 21 <!--注冊一個觸發器,指定任務觸發的時間(間隔)--> 22 <bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> 23 <property name="jobDetail" ref="clearImgJobDetail"/> 24 <property name="cronExpression"> 25 <!-- 每隔10秒執行一次任務 0/10 * * * * ? --> 26 <!-- 每隔2分鍾執行一次任務 0 0/2 * * * ? --> 27 <!-- 每天凌晨2點執行一次任務 0 0 2 * * ? --> 28 <value>0/10 * * * * ?</value> 29 </property> 30 </bean> 31 <!--注冊一個統一調用工廠,通過這個調度工廠調度任務--> 32 <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 33 <property name="triggers"> 34 <list> 35 <ref bean="jobTrigger"/> 36 </list> 37 </property> 38 </bean> 39 </beans>
(5)修改web.xml,容器啟動時,加載spring配置文件
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app> 6 <display-name> Jobs Web Application</display-name> 7 <context-param> 8 <param-name>contextConfigLocation</param-name> 9 <param-value>classpath:spring-*.xml</param-value> 10 </context-param> 11 <listener> 12 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 13 </listener> 14 </web-app>
執行上面main方法觀察控制台,可以發現每隔10秒會輸出一次,說明每隔10秒自定義Job被調用一次。
上面的入門案例中我們指定了一個表達式:0/10 * * * * ?
這種表達式稱為cron表達式,通過cron表達式可以靈活的定義出符合要求的程序執行的時間。
4.
本節基於Quartz定時任務,通過計算redis兩個集合的差值找出所有的垃圾圖片,就可以將垃圾圖片清理掉。
實現流程:
1.
需要進行差值計算
2.
修改為每天凌晨2點執行任務
3.
增加刪除方法
4.
進行差值計算,對差值結果就是需要清理的圖片
操作步驟:
(1) 配置spring-redis.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 6 <property name="maxTotal"> 7 <value>200</value> 8 </property> 9 <property name="minIdle"> 10 <value>50</value> 11 </property> 12 <property name="testOnBorrow" value="true"/> 13 <property name="testOnReturn" value="true"/> 14 </bean> 15 <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> 16 <constructor-arg name="poolConfig" ref="jedisPoolConfig"/> 17 <constructor-arg name="host" value="127.0.0.1"/> 18 <constructor-arg name="port" value="6379"/> 19 </bean> 20 </beans>
(2) 修改spring-jobs.xml,調度時間改為每天凌晨2點執行
0 0 2 * * ?
1 <!--注冊一個觸發器,指定任務觸發的時間(間隔)--> 2 <bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> 3 <property name="jobDetail" ref="clearImgJobDetail"/> 4 <property name="cronExpression"> 5 <!--每隔10秒執行一次任務 0/10 **** ?--> 6 <!--每隔2分鍾執行一次任務 0 0/2 *** ?--> 7 <!--每天凌晨2點執行一次任務 0 0 2 ** ?--> 8 <value>0 0 2 * * ?</value> 9 </property> 10 </bean>
(3)增加七牛工具類,刪除不用的文件
1 /** 2 * 七牛雲工具類 3 */ 4 public class QiniuUtils { 5 public static String accessKey = "fhuiPBXFTZIgJdtZGuMtCUJ3zSrT7k3AHmVNE4UA"; 6 public static String secretKey = "zKKxCW_HjQmwtl4JI80nMT0Ve2V7VZDbqT4zt_tT"; 7 public static String bucket = "itcast_health"; 8 9 /** 10 * 刪除文件 11 * @param fileName 服務端文件名 12 */ 13 public static void deleteFileFromQiniu(String fileName){ 14 //構造一個帶指定Zone對象的配置類 15 Configuration cfg = new Configuration(Zone.zone0()); 16 String key = fileName; 17 Auth auth = Auth.create(accessKey, secretKey); 18 BucketManager bucketManager = new BucketManager(auth, cfg); 19 try { 20 bucketManager.delete(bucket, key); 21 } catch (QiniuException ex) { 22 //如果遇到異常,說明刪除失敗 23 System.err.println(ex.code()); 24 System.err.println(ex.response.toString()); 25 } 26 } 27 // 測試上傳與刪除 28 public static void main(String args[]) throws Exception{ 29 // 測試刪除 30 //deleteFileFromQiniu("f5eee75c0c5d4eeda1c5c49bee766603"); 31 } 32 }
(4)修訂ClearJob定時任務類
1 /** 2 * 定時任務:清理垃圾圖片 3 */ 4 public class ClearJob { 5 @Autowired//idea自動識別,xml文件頂部出現的context中勾選全部xml文件,就能正常識別了 6 private JedisPool jedisPool; 7 //清理圖片 8 public void clearImageJob(){ 9 //計算redis中兩個集合的差值,獲取垃圾圖片名稱 10 Set<String> set = jedisPool.getResource() 11 .sdiff(RedisConst.SETMEAL_PIC_RESOURCES, 12 RedisConst.SETMEAL_PIC_DB_RESOURCES); 13 Iterator<String> iterator = set.iterator(); 14 while(iterator.hasNext()){ 15 String pic = iterator.next(); 16 //刪除圖片服務器中的圖片文件 17 QiniuUtils.deleteFileFromQiniu(pic); 18 //刪除redis中的數據 19 jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES,pic); 20 } 21 } 22 }
