Quartz
-
简介:Quartz是Job scheduling(作业调度)领域的一个开源项目,Quartz既可以单独使用也可以跟spring框架整合使用,在实际开发中一般会使用后者。使用Quartz可以开发一个或者多个定时任务,每个定时任务可以单独指定执行的时间,例如每隔1小时执行一次、每个月第一天上午10点执行一次、每个月最后一天下午5点执行一次等。
-
Spring整合Quartz 依赖导入 定时删除图片
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>meinian_parent</artifactId> <groupId>com.atguigu</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>meinian_jobs</artifactId> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>com.atguigu</groupId> <artifactId>meinian_interface</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz-jobs</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <!-- 指定端口 --> <port>83</port> <!-- 请求路径 --> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
-
配置web.xml
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoadListerner</listener-class> </listener>
-
配置applicationContext-redis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--Jedis连接池的相关配置--> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!--在指定时刻通过pool能够获取到的最大的连接的jedis个数--> <property name="maxTotal"> <value>200</value> </property> <!--最大能够保持idle的数量--> <property name="maxIdle"> <value>50</value> </property> <!--表示连接池在创建链接的时候会先测试一下链接是否可用,这样可以保证连接池中的链接都可用的。--> <property name="testOnBorrow" value="true"/> <property name="testOnReturn" value="true"/> </bean> <bean id="jedisPool" class="redis.clients.jedis.JedisPool"> <constructor-arg name="poolConfig" ref="jedisPoolConfig" /> <constructor-arg name="host" value="127.0.0.1" /> <constructor-arg name="port" value="6379" type="int" /> <constructor-arg name="timeout" value="30000" type="int" /> </bean> </beans>
-
配置applicationContext-jobs.xml
<!-- 开启配置注解支持 --> <context:component-scan base-package=""></context:component-scan> <!-- 注册自定义job --> <bean id = "jobDemo" class = "jack.sun"></bean> <!-- 注册JobDetail 作用是通过反射指定的Job --> <bean id = "jobDetail" class = "org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 注入目标对象 <property name = "targetObject" ref = "jobDemo"></property> 注入目标方法 <property name = "targetMethod" ref = "clearImg"></property> </bean> 注册一个触发器 <bean id = "myTrigger" class ="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> 注入jobDetail <property name = "jobDetail" ref ="jobDetail"></property> 指定触发的时间 <property name = "cronExpression"> <value>0 0 2 * * ?</value> </property> </bean> 注册一个调度工厂 通过工厂调度任务 <bean id = "scheduler" class = "org.springframework.scheduling.quartz.SchedulerFactoryBean"> 注册多个触发器 <propertty name = "triggers"> <list> <ref bean = "myTrigger"></ref> </list> </propertty> </bean>
-
创建定时任务类
public class ClearImgJob { @Autowired private JedisPool jedisPool; //清理图片 public void clearImg(){ //计算redis中两个集合的差值,获取垃圾图片名称 // 需要注意:在比较的时候,数据多的放到前面,如果pic多,那么pic放到前面,db多,db放到前面 Set<String> set = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES,RedisConstant.SETMEAL_PIC_DB_RESOURCES); Iterator<String> iterator = set.iterator(); while(iterator.hasNext()){ String pic = iterator.next(); System.out.println("删除图片的名称是:"+pic); //删除图片服务器中的图片文件 QiniuUtils.deleteFileFromQiniu(pic); //删除redis中的数据 jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,pic); } } }
-
工具类
/** * 七牛云工具类 */ public class QiniuUtils { public static String accessKey = "6wXsRKQW6dprHho6hIOwM7oCY_MITYrhTNKuJzfi"; public static String secretKey = "xEocjgAGkTts3msIWmcL16J6BfMwomfmP5c84zcX"; public static String bucket = "atguigumeinian"; public static void upload2Qiniu(String filePath,String fileName){ //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone2()); UploadManager uploadManager = new UploadManager(cfg); Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(filePath, fileName, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); } catch (QiniuException ex) { Response r = ex.response; try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { //ignore } } } //上传文件 public static void upload2Qiniu(byte[] bytes, String fileName){ //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone2()); //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = fileName; Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(bytes, key, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(putRet.key); System.out.println(putRet.hash); } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); try { System.err.println(r.bodyString()); } catch (QiniuException ex2) { //ignore } } } //删除文件 public static void deleteFileFromQiniu(String fileName){ //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone2()); String key = fileName; Auth auth = Auth.create(accessKey, secretKey); BucketManager bucketManager = new BucketManager(auth, cfg); try { bucketManager.delete(bucket, key); } catch (QiniuException ex) { //如果遇到异常,说明删除失败 System.err.println(ex.code()); System.err.println(ex.response.toString()); } } /* @Test public void test2() throws IOException { //QiniuUtils.upload2Qiniu("D:\\temp\\90\\jjy94.jpg","jjy94.jpg"); //QiniuUtils.deleteFileFromQiniu("jjy94.jpg"); File file = new File("D:\\temp\\90\\jjy94.jpg"); //init array with file length byte[] bytesArray = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(bytesArray); //read file into bytes[] QiniuUtils.upload2Qiniu(bytesArray,"jjy94.jpg"); }*/ }