1 17 18 21 package org.quartz.jobs; 22 23 import java.io.File ; 24 25 import org.quartz.JobDataMap; 26 import org.quartz.JobExecutionContext; 27 import org.quartz.JobExecutionException; 28 import org.quartz.SchedulerContext; 29 import org.quartz.SchedulerException; 30 import org.quartz.StatefulJob; 31 32 import org.apache.commons.logging.Log; 33 import org.apache.commons.logging.LogFactory; 34 35 45 public class FileScanJob implements StatefulJob { 46 47 public static String FILE_NAME = "FILE_NAME"; 48 public static String FILE_SCAN_LISTENER_NAME = "FILE_SCAN_LISTENER_NAME"; 49 private static String LAST_MODIFIED_TIME = "LAST_MODIFIED_TIME"; 50 51 private final Log log = LogFactory.getLog(getClass()); 52 53 public FileScanJob() { 54 } 55 56 59 public void execute(JobExecutionContext context) throws JobExecutionException { 60 JobDataMap mergedJobDataMap = context.getMergedJobDataMap(); 61 SchedulerContext schedCtxt = null; 62 try { 63 schedCtxt = context.getScheduler().getContext(); 64 } catch (SchedulerException e) { 65 throw new JobExecutionException("Error obtaining scheduler context.", e, false); 66 } 67 68 String fileName = mergedJobDataMap.getString(FILE_NAME); 69 String listenerName = mergedJobDataMap.getString(FILE_SCAN_LISTENER_NAME); 70 71 if(fileName == null) { 72 throw new JobExecutionException("Required parameter '" + 73 FILE_NAME + "' not found in merged JobDataMap"); 74 } 75 if(listenerName == null) { 76 throw new JobExecutionException("Required parameter '" + 77 FILE_SCAN_LISTENER_NAME + "' not found in merged JobDataMap"); 78 } 79 80 FileScanListener listener = (FileScanListener)schedCtxt.get(listenerName); 81 82 if(listener == null) { 83 throw new JobExecutionException("FileScanListener named '" + 84 listenerName + "' not found in SchedulerContext"); 85 } 86 87 long lastDate = -1; 88 if(mergedJobDataMap.containsKey(LAST_MODIFIED_TIME)) { 89 lastDate = mergedJobDataMap.getLong(LAST_MODIFIED_TIME); 90 } 91 92 long newDate = getLastModifiedDate(fileName); 93 94 if(newDate < 0) { 95 log.warn("File '"+fileName+"' does not exist."); 96 return; 97 } 98 99 if(lastDate > 0 && (newDate != lastDate)) { 100 log.info("File '"+fileName+"' updated, notifying listener."); 102 listener.fileUpdated(fileName); 103 } else if (log.isDebugEnabled()) { 104 log.debug("File '"+fileName+"' unchanged."); 105 } 106 107 context.getJobDetail().getJobDataMap().put(LAST_MODIFIED_TIME, newDate); 109 } 110 111 protected long getLastModifiedDate(String fileName) { 112 113 File file = new File (fileName); 114 115 if(!file.exists()) { 116 return -1; 117 } else { 118 return file.lastModified(); 119 } 120 } 121 } 122 | Popular Tags |