基于maven发送邮件系列(2)---用spring的timer实现定时发送邮件

时间:2023-01-28 07:54:38

参考的别人的代码,自己写了一下发送邮件的定时任务

以下是文档目录:

基于maven发送邮件系列(2)---用spring的timer实现定时发送邮件

基于maven发送邮件系列(2)---用spring的timer实现定时发送邮件

基于上一次的发送邮件,进一步实现定时

package com.test.listener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.logging.Logger;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.acount.email.AcountEmailException;
import com.test.acount.email.AcountEmailService;

public class TaskTimer extends TimerTask {
private static Logger log = Logger.getLogger(TaskTimer.class.getName());

@Override
public void run() {
setMailTimer();

}

public String getUserSendEmailTime(String time) {
int hour = 0;
int minute = 0;
if (time.equals("") || time == null) {
hour = 17;
minute = 31;//时间自己定义的比如这个是17:31分

} else {
String[] times = time.split(":");
time = times[0];
hour = Integer.parseInt(time);
minute = Integer.parseInt(times[1]);

}
String m = String.valueOf(minute);
String h = String.valueOf(hour);
if (hour == 0 || hour < 10) {// 当小时为0点或是小于10点,和系统当前时间的格式进行匹配
h = "0" + h;
}
if (minute == 0 || minute < 10)// 当分钟为0点或是小于10时,和系统当前时间的格式进行匹配
m = "0" + m;
String dataTime = h + ":" + m;
return dataTime;
}

public void setMailTimer() {

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String nowTime = sdf.format(date);
String userSendEmailTime = getUserSendEmailTime("");
if (nowTime.equals(userSendEmailTime)) {
ClassPathXmlApplicationContext cxa=new ClassPathXmlApplicationContext("acount-email.xml");
AcountEmailService acountEmailService = (AcountEmailService) cxa.getBean("acountEmailService");
String html = "test hahha ";
try {
acountEmailService.sendEmail("XXX@XX.com",
"hello world", html);
} catch (AcountEmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}
2

package com.test.listener;

import java.util.Timer;
import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyTimerTask implements ServletContextListener{
@SuppressWarnings("unused")
private static Logger log =Logger.getLogger(MyTimerTask.class.getName());
private Timer timer = null;
public void contextDestroyed(ServletContextEvent event){
timer.cancel();
}
public void contextInitialized(ServletContextEvent event){
timer = new Timer(true);

timer.schedule(new TaskTimer(),0,60*1000);//服务器启动没有延迟,每一分钟检验一次


}

}
3web.xml 配置监听器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>com.test.listener.MyTimerTask</listener-class>
</listener>
</web-app>