Spring 的强大又体现出来了,相较于 JDK 定时器来说 SPRING 定时器可以做的更多更好,使用起来也相对复杂,今天就为大家带来一个简易版的定时器,并且使用他实现定时邮件发送功能。
具体详细的功能和简介这里就不多说了,直接带大家做一遍:
一段可运行的代码比说很多废话强得多
S1:编写定时任务类(继承 QuartzJobBean )
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
<!-- 配置邮件 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:配置完毕,启动项目就可以启动定时任务,定时发送邮件
上下文根配置(这里简单的使用 servlet 和 一个常量类 constant 来实现)
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 触发器时间配置网络上有很多参考资料,这里不再赘述
如果大家有不明白的可以留言问我,一同进步