上一篇文章实现了图片的上传功能,这里需要做一个删除过期图片的功能,过期时间暂定为 两个星期,即14天
pom.xml 中添加:
<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz --> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
spring配置文件:
<!-- 定义目标bean和bean中的方法 --> <bean id="SpringQtzJob" class="yi.survey.DeleteQuartz" /> <!-- 项目中要执行的类 --> <bean id="SpringQtzJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="SpringQtzJob" /> <!-- 要执行的bean --> </property> <property name="targetMethod"> <!-- 要执行的方法名称 --> <value>delete</value> </property> </bean> <!-- ======================== 调度触发器 ======================== --> <bean id="CronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="SpringQtzJobMethod"></property> <!-- 要执行的计划 --> <property name="cronExpression" value="0 0 0 * * ?"></property> <!-- 触发时间 此为每天0点启动 --> </bean> <!-- ======================== 调度工厂 ======================== --> <bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="CronTriggerBean" /> <!-- 执行触发器 --> </list> </property> </bean>
DeleteQuartz.java类
public class DeleteQuartz { public void delete(){ System.out.println(new Date()+"触发定时器"); String basePath= System.getProperty("SMBMMVC.root"); String imgPath=basePath+"statics/img"; File file=new File(imgPath); File[] files = file.listFiles(); for (File file1 : files) { String fileName=file1.getName(); if(!fileName.contains("timeOut")){ String baseName = FilenameUtils.getBaseName(fileName); String[] s = baseName.split("_"); Date date=new Date(Long.parseLong(s[2])); //获取图片上传日期 //当前日期 Calendar calendar=Calendar.getInstance(); Date nowTime = calendar.getTime(); //图片上传日期第14天的日期 calendar.setTime(date); calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR)+14); Date outTime = calendar.getTime(); if(nowTime.after(outTime)){ //当前日期在过期日期之后 System.out.println("删除过期照片:"+ fileName); file1.delete(); } } } } }