先在工程的web.xml文件中添加以下内容:
<listener>
<listener-class>com.zrzt.atl.web.utils.AutoDeletedoc</listener-class>
</listener>
其中AutoDeletedoc是定时器工具类
package com.zrzt.atl.web.utils;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.jfinal.kit.PathKit;
/**
* Description : 自动删除缓存文件定时器
* <p>
* Created by deron on 2018/1/23.
*/
public class AutoDeletedoc implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// web停止时执行
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// web 启动时执行
String path = PathKit.getWebRootPath() + "\\download";
File file = new File(path);
try {
Timer timer = new Timer();// 定时删除文件定时器
TimerTask task = new TimerTask() {
public void run() {
try {
AutoDeletedoc.deleteAllFilesOfDir(file);
System.out.println("删除下载缓存文件!");
} catch (Exception e) {
e.printStackTrace();
}
}
};
try {
timer.schedule(task, 0, 600000);// 每600秒取一次
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public static void deleteAllFilesOfDir(File path) {
if (!path.exists())
return;
if (path.isFile()) {
path.delete();
return;
}
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
deleteAllFilesOfDir(files[i]);
}
path.delete();
}
}