Quartz快速开发
application-quartz.xml
需要将本文件加载到IOC容器中
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解配置支持,否则在ClearImgJob不能使用@Autowired-->
<context:component-scan base-package="com.xxx"></context:component-scan>
<!-- 注册自定义Job -->
<bean id="jobDemo" class="com.xxx.job.ClearImgJob"></bean>
<!-- 注册JobDetail,作用是负责通过反射调用指定的Job -->
<bean id="jobDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 注入目标对象 -->
<property name="targetObject" ref="jobDemo"/>
<!-- 注入目标方法 -->
<property name="targetMethod" value="clearImg"/>
</bean>
<!-- 注册一个触发器,指定任务触发的时间 -->
<bean id="myTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!-- 注入JobDetail -->
<property name="jobDetail" ref="jobDetail"/>
<!-- 指定触发的时间,基于Cron表达式(0 0 2 * * ?表示凌晨2点执行) -->
<!-- 指定触发的时间,基于Cron表达式(0 25 12 * * ?表示12点25分执行) -->
<property name="cronExpression">
<value>0 55 17 * * ?</value>
</property>
</bean>
<!-- 注册一个统一的调度工厂,通过这个调度工厂调度任务 -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 注入多个触发器 -->
<property name="triggers">
<list>
<ref bean="myTrigger"/>
</list>
</property>
</bean>
</beans>
java
package com.xxx.job;
import com.xxx.constant.RedisConstant;
import com.xxx.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;
import java.util.Iterator;
import java.util.Set;
public class ClearImgJob {
@Autowired
private JedisPool jedisPool;
// 清理图片
public void clearImg(){
// 计算两个集合的差异
Set<String> set = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String img = iterator.next();
System.out.println("删除图片的名称是:" + img);
// 删除图片服务器中的多余图片
QiniuUtils.deleteFileFromQiniu(img);
// 删除redis中的数据
jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,img);
}
}
}