首页 > 代码库 > Spring 定时器 定时访问数据库并发送邮件
Spring 定时器 定时访问数据库并发送邮件
我这里有两个案例的方法:
第一种:使用Spring quartz:
我这里使用的jar:spring-context-support.jar、quartz-1.6.5.jar
==============applicationContext.xml配置=================
<!--定时器service-->
<bean id="timerTaskServices" class="com.gzbugu.service.TimerTaskServices.impl.TimerTaskServicesImpl" >
<property name="commonDao" ref="commonDao"/>
</bean>
<bean id="checkYsyj" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="timerTaskServices" /><!--托管业务层-->
</property>
<property name="targetMethod">
<value>checkYsTarsk</value><!--执行的方法-->
</property>
</bean>
<!--执行时间-->
<bean id="checkYsyjTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<!-- 多个可用 <property name="jobDetail" ref="job****" />-->
<!--名称必须:jobDetail,否则会报错-->
<property name="jobDetail"><ref bean="checkYsyj" /></property>
<property name="cronExpression">
<!-- 每天凌晨23:50分执行 -->
<!-- <value>0 50 23 * * ?</value> -->
<!--一秒钟调用一次-->
<value>0/1 * * * * ?</value>
</property>
</bean>
<!--定时器列表-->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean" >
<property name="triggers">
<list><ref local="checkYsyjTrigger" /></list>
</property>
<!--
启用jobstore的RAMJobStore(内存存储的)模式,配置如下:
<property name="quartzProperties"> <props>
<prop key="org.quartz.jobStore.class">org.quartz.simpl.RAMJobStore</prop>
</props>
</property>
-->
</bean>
================web.xml配置(注:spring环境配置不写了)========================
<!-- Spring 监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
=================业务方法==========================
public class TimerTaskServicesImpl implements TimerTaskServices {
public ICommonDao commonDao;
@Override
public void checkYsTarsk() {
System.out.println("调用成功....");
String hql = " from ProjectBase o ";
List<ProjectBase> list=commonDao.findByHql(hql);//访问数据库
System.out.println(list.get(0).getProjectName());
sendEmail("发送人的邮箱", "收件人的邮箱","发件人的密码","标题","内容");//发送邮件方法
System.out.println("执行成功....");
}
/**
* http://www.cnblogs.com/qgc88/
* @param sendFrom
* 发送方
* @param sendTo
* 接收方
* @param passWord
* 发送方邮箱密码
* @param title
* 发送标题
* @param count
* 发送内容
* @return success 和 error
*/
public static String sendEmail(String sendFrom, String sendTo,
String passWord, String title, String count) {
try {
String from = sendFrom.trim();// 发送者
String to = sendTo.trim();// 接受者
String subject = title.trim();// 主题
String content = count.trim();// 内容
String password = passWord.trim();// 发送者邮箱密码
String path = "null";// 附件的路径
String mailserver = "smtp."
+ from.substring(from.indexOf(‘@‘) + 1, from.length()); // 在Internet上发送邮件时的代码(smtp服务器地址)
// String mailserver = "wanggh"; //在局域网内发送邮件时的代码
Properties prop = new Properties();
prop.put("mail.smtp.host", mailserver);
prop.put("mail.smtp.auth", "true");
prop.put("mail.transport.protocol", "smtp");
Session sess = Session.getDefaultInstance(prop);
sess.setDebug(true);
// 设定传送邮件的发信人
MimeMessage message = new MimeMessage(sess);
message.setFrom(new InternetAddress(from)); // 给消息对象设置发件人
// 设置收件人
String toArr[] = to.split(",");
InternetAddress[] to_mail = new InternetAddress[toArr.length];
for (int i = 0; i < toArr.length; i++) {
to_mail[i] = new InternetAddress(toArr[i]);
}
message.setRecipients(Message.RecipientType.BCC, to_mail);
// 设置主题
message.setSubject(subject);
Multipart mul = new MimeMultipart(); // 新建一个MimeMultipart对象来存放多个BodyPart对象
BodyPart mdp = new MimeBodyPart(); // 新建一个存放信件内容的BodyPart对象
mdp.setContent(content, "text/html;charset=gb2312");
mul.addBodyPart(mdp); // 将含有信件内容的BodyPart加入到MimeMulitipart对象中
if (!"null".equals(path)) { // 当存在附件时
// 设置信件的附件(用本机上的文件作为附件)
mdp = new MimeBodyPart(); // 新建一个存放附件的BodyPart
String adjunctname = new String(path.getBytes("GBK"),
"ISO-8859-1"); // 此处需要转码,否则附件中包括中文时,将产生乱码
path = (System.getProperty("java.io.tmpdir") + "/" + path)
.replace("\\", "/");
System.out.println("路径:" + path);
FileDataSource fds = new FileDataSource(path);
DataHandler handler = new DataHandler(fds);
mdp.setFileName(adjunctname);
mdp.setDataHandler(handler);
mul.addBodyPart(mdp);
}
message.setContent(mul); // 把mul作为消息对象的内容
message.saveChanges();
Transport transport = sess.getTransport("smtp");
// 以smtp方式登录邮箱,第1个参数是发送邮件用的邮件服务器SMTP地址,第2个参数为用户名,第3个参数为密码
// qq邮箱POP3服务器(端口995)
// SMTP服务器(端口465或587)
transport.connect(mailserver, from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return "success";
} catch (Exception e) {
System.out.println(e.getMessage());
return "error";
}
}
public ICommonDao getCommonDao() {
return commonDao;
}
public void setCommonDao(ICommonDao commonDao) {
this.commonDao = commonDao;
}
}
=================方法一结束========================
------------------------------------------------------------------------------
===================方法二===============
package com.qgc.card.JTool;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.qgc.card.services.servicesImpl.MessageServicesImpl;
/**
* 定时器
* @author http://www.cnblogs.com/qgc88/
*
*/
public class MyTimerTask implements ServletContextListener {
private Timer timer = null;
@Override
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
System.out.println("定时器销毁");
}
@Override
public void contextInitialized(ServletContextEvent event) {
//在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
timer = new Timer(true);
event.getServletContext().log("定时器已启动");//添加日志,可在tomcat日志中查看到
timer.schedule(new MessageServicesImpl(event.getServletContext()),0,24*60*60*1000);//一天调用一次类MessageServicesImpl
System.out.println("定时器已启动");
}
}
=================MessageServicesImpl=============================
package com.qgc.card.services.servicesImpl;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import com.qgc.card.services.UserServices;
/**
* 定时器的类
*
* @author http://www.cnblogs.com/qgc88/
*
*/
public class MessageServicesImpl extends TimerTask {
private ServletContext context = null;
public MessageServicesImpl(ServletContext context) {
this.context = context;
}
@Override
public void run() {
timeMessage();//方法
}
public ServletContext getContext() {
return context;
}
public void setContext(ServletContext context) {
this.context = context;
}
}
@SuppressWarnings("deprecation")
public void timeMessage(){
JToolAccess jdbc=new JToolAccess();//工具类
Users users=new Users();
try {
Connection conn=jdbc.qryConnJDBC();
System.out.println("监听成功..");
jdbc.ps = conn.prepareStatement("select * from Users where statsu<>‘-1‘ ");
ResultSet rss = jdbc.ps.executeQuery();
while (rss.next()) {
System.ou.println(rss.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("监听异常:"+e.getMessage());
}finally{
jdbc.closeConn();
}
}
==================jdbc工具类JToolAccess===========================
package com.qgc.card.JTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
public class JToolAccess {
public ResultSet rs = null;
public PreparedStatement ps = null;
public Connection conn = null;
public void closeConn() {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Properties getProperties() {
Properties properties = new Properties();
try {
String getURL=getClass().getResource("/").getPath();
System.out.println(getURL + "META-INF/db.Properties");
File file = new File(getURL + "META-INF/db.Properties");
if (!file.exists()) {
file.createNewFile();
properties
.setProperty("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
properties.setProperty("dialect",
"org.hibernate.dialect.SQLServerDialect");
}
FileInputStream inStream = new FileInputStream(file);
properties.load(inStream);
inStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
public Connection qryConnJDBC() {
try {
String url =getProperties().getProperty("url");
Class.forName(getProperties().getProperty("driver"));
conn = DriverManager.getConnection(url,getProperties().getProperty("uname"),getProperties().getProperty("pwd"));
System.out.println("数据库连接成功!");
} catch (Exception e) {
System.out.println("数据库连接失败,系统消息为:" + e.getMessage()
+ ",请检查您的数据库信息!");
}
return conn;
}
public PreparedStatement getPs() {
return ps;
}
public void setPs(PreparedStatement ps) {
this.ps = ps;
}
public ResultSet getRs() {
return rs;
}
public void setRs(ResultSet rs) {
this.rs = rs;
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
}
==========web.xml配置(注:spring环境配置不写了)===================
<!-- 定时器-->
<listener>
<listener-class>com.qgc.card.JTool.MyTimerTask</listener-class>
</listener>
Spring 定时器 定时访问数据库并发送邮件