Quartz Spring 定时器入门到使用

    xiaoxiao2021-03-25  151

    本文属原创,转载请注明来源:http://blog.csdn.net/wuqilianga/article/details/60874060

    任务需求: 定时清理文件,每小时检查一次,隔设定的时间的文件进行删除处理

    使用到的技术: Quartz Spring 定时器

    使用的过程,需要搭建好了架构的web项目

    简单明了的实现说明:建立项目-配置xml定时任务--实现ThreadJob任务定时处理

    需要的jar如下:

    spring-context-support-3.1.2.RELEASE.jar

    具体步骤:

    1.WEB-INF下的web.xml中进行配置相应的扫描路径,告诉系统定时器在哪里 

    图 - - web.xml文件所在目录

    配置路径和存放文件schedule_job.xml文件如下:

    <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:context/*.xml</param-value> </context-param>

    图 - - 左侧为web.xml配置文件指明schedule_job.xml配置文件存放位置,右侧为web.xml配置清单列表

    2.schedule_job.xml配置文件内容如下:

    <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 删除文件--> <bean id="DynamicFileDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <bean class="com.xxx.framework.job.DeleteDynamicFilesJob"/> </property> <!-- 定时Job中执行的方法里不能再次创建线程,否则会报错 --> <property name="targetMethod" value="run"/> <property name="concurrent" value="false"/> </bean> <bean id="DynamicFileCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="DynamicFileDetail"/> <property name="cronExpression"> <!-- 每小时 xx:00 --> <value>0 0 * ? * *</value> </property> </bean> <!-- 收集所有定时器 --> <bean id="schedulerFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref local="DynamicFileCronTrigger"/> </list> </property> </bean> </beans>

    在这里说明一下:

    这份配置和spring的beans那种配置一样,Factory工厂模式管理所有的Trigger触发器,而每个Triger触发器管理一个Job的工作,这里存在这依赖注入关系,需要一点spring

    的配置知识,其中这里有个cron定时功能,就是上边配置的<value>0 0 * ? * *</value>这个配置表达式叫做cron表达式,就是要指定定时器多久触发一次,总共有七个参数,第七个参数可忽略,代表年,参数之间用空格分开,分表代表 秒 分 时 月份天数 月 月份星期 年,本文配置中年没用到,具体的用法及简介可参看下边链接 详细说明:点击打开链接

    3.删除的Job定时工作类非常简单:

    public class DeleteDynamicFilesJob extends Thread{ private final Logger LOG = LoggerFactory.getLogger(getClass()); @Override public void run() { try { //这里进行异步处理你的定时事项,我这里是定时清理文件 /*** *** 注意:定时Job中执行的方法里不能再次创建线程,否则会报错 ***/ FileUtil.deleteDynamicFiles(); } catch (Exception e) { LOG.error("--", e); } } }

    FileUtil清单如下:

    public class FileUtil { private static final Logger LOG = Logger.getLogger(FileUtil.class); /** * 判断上载文件是否为xls文件。 * * @param file * @return boolean */ public static boolean isXls(File file) { String fileName = file.getName(); if (fileName.endsWith(".XLS") || fileName.endsWith(".xls")) { return true; } return false; } /** * 保存上载文件到特定目录下,文件名不变。 * * @param File * file 文件对象. * @param String * filePath 保存文件的绝对路径,如:C:\\temp. */ public static void saveUploadFile(File file, String filePath) { saveUploadFile(file, null, filePath); } /** * 保存上载文件到特定目录下,并且改变文件名。如果saveAsFileName为null则取原来的文件名称。 * * @param File * file 文件对象. * @param String * filePath 保存文件的绝对路径,如:C:\\temp. */ public static String saveUploadFile(File file, String saveAsFileName, String filePath) { String fileName = saveAsFileName; if (fileName == null) { fileName = file.getName(); } try { FileInputStream stream = new FileInputStream(file); File dir = new File(filePath); createFolder(dir); fileName = filePath + System.getProperty("file.separator") + fileName; OutputStream bos = new FileOutputStream(fileName); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } stream.close(); bos.flush(); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } return fileName; } /** * 根据相对路径,得到绝对路径.如果目录不存在,则创建相应目录. * * @param request * @param uriPath * 相对路径,如/Module/Upload,必须以"/"开头。 * @return */ public static String getRealPath(HttpServletRequest request, String uriPath) { String path = request.getSession().getServletContext().getRealPath( uriPath); java.io.File newDir = new java.io.File(path); if (!newDir.exists()) { // 路径不存在,则创建. newDir.mkdirs(); } return path; } /** * 根据相对路径,得到绝对路径.如果目录存在,则删除相应目录. * * @param request * @param uriPath * 相对路径,如/Module/Upload,必须以"/"开头。 * @return */ public static boolean deleteRealPath(HttpServletRequest request, String uriPath) { try{ String path = request.getSession().getServletContext().getRealPath( uriPath); delFolder(path); }catch (Exception e) { e.printStackTrace(); return false; } return true; } // 删除文件夹 // param folderPath 文件夹完整绝对路径 public static void delFolder(String folderPath) { try { delAllFile(folderPath); // 删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); // 删除空文件夹 } catch (Exception e) { e.printStackTrace(); } } // 删除指定文件夹下所有文件 // param path 文件夹完整绝对路径 public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件 delFolder(path + "/" + tempList[i]);// 再删除空文件夹 flag = true; } } return flag; } public static boolean createFolder(File file){ if(!file.exists()){ if(!file.getParentFile().exists()){ return createFolder(file.getParentFile()); } return file.mkdirs(); } return true; } /** * 定时删除临时文件 * @author: Dicky * @time: 2015-5-21 22:50:28 * @version: 1.0 */ public static void deleteDynamicFiles() { String dynamic = FFProperties.getPropertyString("framework.share.folder")+"/dynamic"; File dy = new File(dynamic); File[] fs = dy.listFiles(); if(fs==null || fs.length==0){ LOG.error("-无文件可删除->"+dynamic); return; } long now = System.currentTimeMillis(); for (int i = 0; i < fs.length; i++) { String name = fs[i].getName(); if(name.endsWith(".zip")){ try{ Long temp = Long.parseLong(name.substring(0, name.length()-4)); if(now-temp>14400000){//4小时之前的文件删除掉 fs[i].delete(); } }catch (Exception e) { LOG.error("-删除文件失败->"+fs[i].getPath(),e); } } try{ Long temp = Long.parseLong(name); if(now-temp>14400000){//4小时之前的文件删除掉 FileUtils.deleteDirectory(fs[i]); } }catch (NumberFormatException e) { }catch (Exception e) { LOG.error("-删除文件失败->"+fs[i].getPath(),e); } } } }

    到这里,本文介绍的spring定时工作实现就完成了!!!

    需要详细了解Quartz等内容,可以参考以下文章:

    http://blog.csdn.net/huihuimimi17/article/details/8215779 --- Quartz http://blog.csdn.net/oracle_microsoft/article/details/4412502-- Spring结合Quartz实现多任务定时调用

    转载请注明原文地址: https://ju.6miu.com/read-2990.html

    最新回复(0)