Spring定时任务注解实现定时清空指定文件夹下的文件

@EnableScheduling和@Scheduled(cron = "0 0 4 * * ?"),通过注解方式实现定时任务:
 1 import org.slf4j.Logger;
 2 import org.slf4j.LoggerFactory;
 3 import org.springframework.scheduling.annotation.EnableScheduling;
 4 import org.springframework.scheduling.annotation.Scheduled;
 5 import org.springframework.stereotype.Component;
 6 import java.io.File;
 7 import java.util.Date;
 8 
 9 /**
10  * Created by xxx on 2018-11-17.
11  */
12 @Component
13 @EnableScheduling
14 public class InitTaskConfig {
15     private static Logger logger = LoggerFactory.getLogger(InitTaskConfig.class);
16     /**
17      *设置定时任务
18      */
19     @Scheduled(cron = "0 0 4 * * ?")
20     public void deleteEmailFileTask(){
21         logger.info ("清空邮件附件临时文件夹的定时任务开始");
22         Date date = new Date(System.currentTimeMillis() - 1000 * 60 * 60*4);
23         File folder = new File(ConfigUtils.get("pdpm.app.delegate.filepath"));
24         File[] files = folder.listFiles();
25         for (int i=0;i<files.length;i++){
26             File file = files[i];
27             if (new Date(file.lastModified()).before(date)){
28                 file.delete();
29             }
30         }
31         logger.info ("清空邮件附件临时文件夹的定时任务结束");
32     }
33 }

本代码实现的了,每天4点,清空指定文件夹下,文件的最后修改时间是上一工作日及之前的所有文件~

posted @ 2018-11-17 21:44  RayChou1995  阅读(871)  评论(0编辑  收藏  举报