您的位置:首页 > 编程语言 > Java开发

java 定时任务,定时删除缓存文件

2017-06-19 13:36 411 查看
//每天零点执行删除tomcat下所有的临时文件,用spring的定时任务注解,防止多余的临时文件占用空间
@Component
public class TestTimer {

@Scheduled(cron="0 0 0 * * ?")      //定时任务,每天零点触发
public void myTimer(){
try {
String path=File.createTempFile("datas", ".txt").getPath();		//获取临时文件路径
File file=new File(path).getParentFile();		//获取临时文件存放的文件夹
File[] files=file.listFiles();				//取文件夹下所有文件
for(File f:files){					//遍历删除所有文件
delete(f);
System.out.println("当前时间是"+new Date().toString());
}
} catch (IOException e) {
e.printStackTrace();
}

}

/**
* 将file文件夹下的所有文件清空
* @param file
*/
private boolean delete(File file){
if (file.isDirectory()) {
String[] children = file.list();
for (int i=0; i<children.length; i++) {     //递归删除目录中的子目录下
delete(new File(file, children[i]));
}
}
// 目录此时为空,可以删除
return file.delete();
}
}

在application.xml里的beans属性中添加
xmlns:task="http://www.springframework.org/schema/task"

然后在beans属性里的 xsi:schemaLocation 属性参数末尾添加
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd 最后在application.xml中增加定时任务配置,自动扫描对应包下的文件。***代表扫描路径

<task:annotation-driven/>
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:component-scan base-package="com.***"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring