Spring 的強大又體現出來了,相較於 JDK 定時器來講 SPRING 定時器能夠作的更多更好,使用起來也相對複雜,今天就爲你們帶來一個簡易版的定時器,而且使用他實現定時郵件發送功能。html
具體詳細的功能和簡介這裏就很少說了,直接帶你們作一遍:java
一段可運行的代碼比說不少廢話強得多web
S1:編寫定時任務類(繼承 QuartzJobBean )spring
TIP:其中 Constant.getPath 是得到項目文件系統絕對路徑,這部分已經在項目啓動時配置到單例當中了,下面會給個簡單實現。至於 JavaMailSenderImpl mailSender 請你們參考我上一篇博文。服務器
/** ******************************************************************************************** * @ClassName: SendEmailTimer * @Description: 定時發送郵件類,定時發送指定路徑下的 PDF * @author ZhouQian * @date 2014-6-12-上午9:44:39 ******************************************************************************************** */ public class SendEmailTimer extends QuartzJobBean { private JavaMailSenderImpl mailSender; @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { try { // 任務執行時間 Date fireTime = context.getFireTime(); // 任務下次執行時間 Date nextFireTime = context.getNextFireTime(); String logContent = "這次運行時間:" + fireTime + ",下次運行時間:" + nextFireTime; System.out.println(logContent); // 發送郵件 // 郵件POJO 對象 MailPojo mailPojo = new MailPojo(); MimeMessage m = mailSender.createMimeMessage(); // 構造附件 String path = "jsp/theme/analyser/hero.html"; path = Constant.get_REALPATH() + path; File[] attachment = new File[1]; String[] attachmentFileName = new String[1]; attachment[0] = new File(path); attachmentFileName[0] = "hero.html"; try { MimeMessageHelper helper = new MimeMessageHelper(m, true, "UTF-8"); // 設置收件人 helper.setTo("xxx@163.com"); // 設置抄送 // helper.setCc(""); // 設置發件人 helper.setFrom("xxx@163.com"); // 設置暗送 // helper.setBcc(""); // 設置主題 helper.setSubject("測試郵件!"); // 設置 HTML 內容 helper.setText("這只是一封測試郵件!若是你收到的話說明我已經發送成功了!"); // 保存附件,這裏作一個 copy 只是爲了防止上傳文件丟失 attachment = saveFiles(attachment, attachmentFileName); for (int i = 0; attachment != null && i < attachment.length; i++) { File file = attachment[i]; // 附件源 FileSystemResource resource = new FileSystemResource(file); helper.addAttachment(attachmentFileName[i], resource); // mail 對象填充 AttachmentPojo attachmentPojo = new AttachmentPojo(); attachmentPojo.setFilename(attachmentFileName[i]); attachmentPojo.setFilepath(file.getAbsolutePath()); mailPojo.getAttachmentPojos().add(attachmentPojo); } // 進行郵件發送和郵件持久類的狀態設定z mailSender.send(m); mailPojo.setSent(true); System.out.println("郵件發送成功!"); } catch (Exception e) { e.printStackTrace(); mailPojo.setSent(false); // TODO: handle exception } } catch (Exception e) { e.printStackTrace(); } } /** * struts 2 會將文件自動上傳到臨時文件夾中,Action運行完畢後臨時文件會被自動刪除 所以須要將文件複製到 /upload 文件夾下 * * @param files * @param names * @return */ public File[] saveFiles(File[] files, String[] names) { if (files == null) return null; File root = new File(Constant.get_REALPATH() + Constant.getFolderName()); File[] destinies = new File[files.length]; for (int i = 0; i < files.length; i++) { File file = files[i]; File destiny = new File(root, names[i]); destinies[i] = destiny; copyFile(file, destiny); } return destinies; } /** * 複製單個文件 * * @param from * @param to */ public void copyFile(File from, File to) { InputStream ins = null; OutputStream ous = null; try { // 建立全部上級文件夾 to.getParentFile().mkdirs(); ins = new FileInputStream(from); ous = new FileOutputStream(to); byte[] b = new byte[1024]; int len; while ((len = ins.read(b)) != -1) { ous.write(b, 0, len); } } catch (Exception e) { // TODO: handle exception } finally { if (ous != null) try { ous.close(); } catch (Exception e) { e.printStackTrace(); } if (ins != null) try { ins.close(); } catch (Exception e) { e.printStackTrace(); } } } public JavaMailSenderImpl getMailSender() { return mailSender; } public void setMailSender(JavaMailSenderImpl mailSender) { this.mailSender = mailSender; } }
S2:定時任務配置,配置 applicationContext.xml網絡
依次配置 郵件 sender -> 定時任務 bean -> 定時任務觸發器 bean -> 定時任務工場 bean
app
<!-- 配置郵件 senderbean --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="${mail.smtp.host}"></property> <property name="javaMailProperties" > <props> <prop key="mail.smtp.auth">${mail.smtp.auth}</prop> <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop> </props> </property> <property name="username" value="${mail.smtp.username}"></property> <property name="password" value="${mail.smtp.password}"></property> </bean> <!-- 定時器任務 START --> <!-- 配置定時郵件任務,須要配置實現類、以及依賴的屬性 --> <bean id="sendEmailTimer" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>com.sesan.dc.common.timer.SendEmailTimer</value> </property> <property name="jobDataAsMap"> <map> <entry key="mailSender"> <ref bean="mailSender"/> </entry> </map> </property> </bean> <!-- 定時器觸發器,配置定時器,以及觸發時機 --> <bean id="timerTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="sendEmailTimer"></property> <property name="cronExpression"> <!-- 秒 分 小時 日 月 周幾 年,每 30 秒執行一次 --> <value>30 * * * * ?</value> </property> </bean> <!-- 定時器工場,能夠配置多個觸發器 --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="timerTrigger"/> </list> </property> </bean> <!-- 定時器任務 END -->
S3:配置完畢,啓動項目就能夠啓動定時任務,定時發送郵件jsp
上下文根配置(這裏簡單的使用 servlet 和 一個常量類 constant 來實現)ide
S1:編寫 Constant 常量持久類,持有一些公關常量測試
public class Constant { // 配置文件路徑 public static final String _CONFIG_FILE = "/baseconfig.properties"; // 項目路徑,可使用單例進行存放 public static String _REALPATH = ""; public static String getConfigFile() { return _CONFIG_FILE; } public static String get_REALPATH() { return _REALPATH; } public static void set_REALPATH(String _REALPATH) { Constant._REALPATH = _REALPATH; } }
S2:編寫 initServlet 來進行項目參數初始化 ....(lol 很土的辦法)
/** * 初始化參數Servlet,服務器啓動自動開始加載 * @author zhouqian * */ public class InitialServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override public void init() throws ServletException { super.init(); System.out.println("開始intitServlet"); String realPath = getServletContext().getRealPath("/"); Constant.set_REALPATH(realPath); } }
S3:web.xml 配置,在 web.xml 設置 InitialServlet 啓動加載
...... 省略 100 字 <servlet> <servlet-name>InitialServlet</servlet-name> <servlet-class>com.sesan.dc.servlet.InitialServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> ...... 省略 100 字
如上配置完畢後就能夠進行定時郵件的發送了,若是定時任務是其餘類型任務只須要修改定時任務類的內容就好了
至於 SPRING 觸發器時間配置網絡上有不少參考資料,這裏再也不贅述
若是你們有不明白的能夠留言問我,一同進步