多语言展示
当前在线:921今日阅读:27今日分享:41

Spring定时任务

功能需求:定时删除项目upload目录下的所有不需要的文件以及目录1.       获取到项目绝对路径2.       删除不需要的文件3.       实现方式spring的定时任务
方法/步骤
1

1.1      实现一个spring的task需要遵循:1.       FileCleatTask类需要使用@Component注解2.       定时任务方法需要注解@Scheduled并且方法不能有返回值和参数

2

1.2      配置spring-task.xml文件                           

3

1.3      编码FileClearTask.java import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat; import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component; @Componentpublic class FileClearTask {     //每天凌晨4:40执行删除图片操作    //@Scheduled(cron='0 40 4 * * ?')    @Scheduled(cron='*/30 * * * * ?')//每5秒执行一次    public void deletePic(){       System.out.println('time='+new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').format(System.currentTimeMillis()));       //列出图片目录的图片       String path = getWebrootPath();       File uploadFile=new File(path,'upload');       if(uploadFile.exists()){           String uploadPath=uploadFile.getAbsolutePath();           if(uploadPath!=null){              deleteFile(uploadPath,uploadPath);           }       }    }    /**     * 获取根目录     * @return     */     private final static String getWebrootPath() {            String root = FileClearTask.class.getResource('/').getFile();            try {                root = new File(root).getParentFile().getParentFile().getCanonicalPath();                root += File.separator;            } catch (IOException e) {                throw new RuntimeException(e);            }            return root;        }    private void deleteFile(String rootPath,String path) {       File pathFile=new File(path);       if(pathFile.exists()){           if(pathFile.isDirectory()){              File[] fileArr = pathFile.listFiles();              for (int i = 0; i < fileArr.length; i++) {                  File childFile=fileArr[i];                  if(childFile.exists()){                     if(childFile.isDirectory()){                         //是目录递归删除                         deleteFile(rootPath,childFile.getAbsolutePath());                     }                     //是文件并且不是根目录并且数据库website中不存在记录删除                    if(!childFile.getAbsolutePath().equals(rootPath)&&!exsitsWebsite(childFile.getName())){                         childFile.delete();                                 }                                     }              }           }           //是文件并且不是根目录并且数据库website中不存在记录删除           if(!pathFile.getAbsolutePath().equals(rootPath)&&!exsitsWebsite(pathFile.getName())){              pathFile.delete();                        }       }    }     /**     * 数据库website表中中是否存在     * @param name     * @return     */    private boolean exsitsWebsite(String name) {       //查询数据库实现数据库是否存在判断...             return false;    }}

推荐信息