1. Web.xml 侦听器注册,最好将侦听器注册代码放置于Spring容器加载侦听服务之下,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>selleck.util.mail.MailListener</listener-class>
</listener>
2.通过实现ServletContextListener接口,实现Servlet侦听器的创建,
package selleck.util.mail;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import selleck.web.email.SendEmails;
public class MailListener extends HttpServlet implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
MailConstant.CarTimer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try{
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext());
MailConstant.setJDBC(applicationContext.getBean("jdbcDAO"));
//注册购物车定时侦听服务
new SendEmails(null,null,null).startCar();
//MailConstant.WriterLine("----------------- 执行购物车定时侦听:" + System.currentTimeMillis());
}catch (Exception e) {
MailConstant.WriterLine("[Error]############### 购物车定时侦听服务 Error:"+e.getMessage());
MailConstant.WriterLine("");
}
}
}
package selleck.web.email;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import selleck.util.ReadProperty;
import selleck.util.mail.MailConstant;
public class SendEmails {
public SendEmails(){}
/**
* 定时器任务制定,执行
* @param tag: 0.在指定的时间里,执行指定的任务;
* 1.在指定的时间里,按照指定的延迟,重复执行指定任务;
* 2.从指定的延迟后,执行指定任务;
* 3.从指定的延迟后,按照指定的延迟,重复执行指定的任务。
*
* @param mydate:指定的执行时间。只有在tag等于0、1才需要指定。
* @param delay: 延迟执行时间,毫秒数。只有在tag等于1、3才需要指定。
* @param period:间隔执行时间,毫秒数。只有在tag等于4才需要指定。
*/
public void startCustomized(int tag) { }
/**
* 定时器任务制定,执行
*/
public void startCar() {
//延迟发送时间
long delay = 1000 ;
long period = new Long(ReadProperty.get("period")) ;
Date mydate = new Date();
MailConstant.CarTimer.schedule(new CarTimerTask(), mydate, 5000);
}
//购物车扫描,定时器任务
private class CarTimerTask extends TimerTask {
public void run() {
emailsSend();
MailConstant.WriterLine("----------------- 执行定时器任务侦听(CarTimerTask):" + System.currentTimeMillis());
}
//邮件群发控制业务
public void emailsSend() {
MailConstant.WriterLine("#################### "+System.currentTimeMillis());
MailConstant.WriterLine("");
try {
List<Object> cars = MailConstant.jdbc.list("SELECT * from table");
if(cars != null){
String compEmail = "xxxxx@xxxxx.xxx";
for(int i=0;i<cars.size();i++){
Map car = (Map)cars.get(i);
emails= car.get("email").toString();
}MailConstant.WriterLine(body);//MailConstant.sendMail(bodyt, compEmail, "this is email title ");}System.out.println("----------------------------3");} catch (Exception e) {MailConstant.WriterLine("[Error]############### 购物车扫描邮件发送 Error:"+e.getMessage());MailConstant.WriterLine("");}}
} }
4.帮助类
package selleck.util.mail;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import selleck.Core.transation.JdbcDAO;
import selleck.Core.transation.imp.JdbcDAOImp;
import selleck.util.ReadProperty;
import com.verticalresponse.api.VrAPI;
public class MailConstant {
//原生态SQL访问
public static JdbcDAO jdbc;
public static void setJDBC(Object obj){
jdbc = (company.Core.transation.JdbcDAO)obj;
}
//时间格式刷
public static SimpleDateFormat sde = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public static SimpleDateFormat sds = new SimpleDateFormat("yyyy-MM-dd");
//生成的文件路径
public static String logPath = new String(ReadProperty.get("logPath"));
public static String systemType = "\r";//new String(ReadProperty.get("systemType"));
//-----------------------------------------------------定时器任务池---------------------------------
//用户个性化定制模式,定时器任务
public static Timer CustomizedTimer = null;
//用户组定制模式,定时器任务
public static Timer GroupTimer = null;
//自定义定时模式,定时器任务
public static Timer CustomTimer = null;
//购物车扫描,定时器任务
public static Timer CarTimer = new Timer();
//-----------------------------------------------------定时器任务池---------------------------------
/**
* 正式模版邮件发送
* @param template
* @param emails
*/
public static String sendMail(String sendContent,String emails,String title){
String val = emails;
try {
//发送邮件接口
} catch (Exception e) {
MailConstant.WriterLine("");
MailConstant.WriterLine("[Error]############### 邮件发送 Error:["+emails+" "+val+"] "+e.getMessage());
MailConstant.WriterLine("");
}
//System.out.println(sendContent+" "+emails+" 邮件发送成功 !");
return val;
}
//获取时间差
public static void dateDiff(String desc,String startTime, String endTime) {
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long between = 0;
try {
java.util.Date begin = dfs.parse(startTime);
java.util.Date end = dfs.parse(endTime);
between = (end.getTime() - begin.getTime());// 得到两者的毫秒数
long day = between / (24 * 60 * 60 * 1000);
long hour = (between / (60 * 60 * 1000) - day * 24);
long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
MailConstant.WriterLine(desc+" 开始时间:"+startTime+" 结束时间:"+endTime);
MailConstant.WriterLine(desc+" 总该耗时:"+day + "天" + hour + "小时" + min + "分" + s + "秒");
} catch (Exception ex) {
ex.printStackTrace();
}
}
//比较两个时间是否存在交集
public static boolean isInDates(String times){
Date dt = new Date();
int strDateH = dt.getHours();
int strDateM = dt.getMinutes();
if(strDateH == 0 && strDateM == 0){
strDateH = 23;strDateM = 59;
}else if(strDateH == 0){
strDateH = 24;
}else if(strDateM == 0){
strDateH = strDateH-1;strDateM = 59;
}
int strDateBeginH = Integer.parseInt(times.split("-")[0].split(":")[0]);
int strDateBeginM = Integer.parseInt(times.split("-")[0].split(":")[1]);
int strDateEndH = Integer.parseInt(times.split("-")[1].split(":")[0]);
int strDateEndM = Integer.parseInt(times.split("-")[1].split(":")[1]);
if(strDateEndH == 0 && strDateEndM == 0){
strDateEndH = 23;strDateEndM = 59;
}else if(strDateEndH == 0){
strDateEndH = 24;
}else if(strDateEndM == 0){
strDateEndH = strDateEndH-1;strDateEndM = 59;
}
if((strDateH>=strDateBeginH && strDateM>=strDateBeginM && strDateH<=strDateEndH && strDateM<=strDateEndM)){
return true;
}else{
return false;
}
}
//写入html文件内容
public static String setLocalHtmlStream(String path,String html) {
//System.out.println(" === "+path);
FileWriter fw;
try {
String head = " <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body> ";
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fw = new FileWriter(path); // "C://Users//Administrator//Desktop//demo//"+System.currentTimeMillis()+".html"
html = head+html+" </body></html> ";
fw.write(html);
fw.flush();
fw.close();
} catch (Exception e) {}
return html;
}
public static File file = null;
//添加Log日志
public static void WriterLine(String val){
try {
String path = MailConstant.logPath+"//"+MailConstant.sds.format(new Date())+".txt";
if(file == null){
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
FileWriter fw = new FileWriter(path,true);
PrintWriter pw = new PrintWriter(fw);
if("".equals(val)){
System.out.println("");
pw.println(systemType);
}else{
System.out.println(val);
pw.println(val+systemType);
}
pw.flush();
fw.flush();
pw.close();
fw.close();
} catch (Exception e) {System.out.println(" Error ######################## Error "+e.getMessage());}
}
}