Spring的任务调度实例

在前面发送邮件的代码基础上,加上spring的任务调度,用来定时发邮件
要加两个包:commons-collections-3.2.jar和包quartz-all-1.6.1.jar
SpringMail.java
package com.yan.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;

import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.activation.FileDataSource;
import javax.activation.DataHandler;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Multipart;

import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

/**
 * spring的邮件发送例子
 * 
 * @author Amigo Xie([email protected])
 * @since 2007/04/28 11:30
 */
public class SpringMail {
    public static ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext-beans.xml");
    public static void main(String[] args) throws Exception {
//        ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext-beans.xml");
//        JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");
//        SpringMail springMail = new SpringMail();
//
//        // 测试发送只有文本信息的简单测试
//        springMail.sendTextMail(sender);

        // 测试发送带附件的邮件
//        springMail.sendMimeMessage(sender);
        System.out.println("*****完毕******"); 
    }
    
    public void sendMail()throws Exception{
      JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");
      SpringMail springMail = new SpringMail();
//      // 测试发送只有文本信息的简单测试
      springMail.sendTextMail(sender);
        
        System.out.println("*****123456******"); 
    }

    /**
     * 测试发送只有文本信息的简单测试
     * 
     * @param sender
     *            邮件发送器
     * @throws Exception
     */
    private void sendTextMail(JavaMailSender sender) throws Exception {
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setTo("[email protected]");
        mail.setFrom("[email protected]");
        mail.setSubject("test by alecyan");
        mail.setText("spring Mail的简单测试");
        sender.send(mail);

        System.out.println("成功发送文本文件!");
    }

    /**
     * 发送带附件的邮件
     * 
     * @param sender
     *            邮件发送器
     * @throws Exception
     */
    private void sendMimeMessage(final JavaMailSender sender) throws Exception {
        // 附件文件集合
        final List files = new ArrayList();
        MimeMessagePreparator mimeMail = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
                mimeMessage.setFrom(new InternetAddress("[email protected]"));
                mimeMessage.setSubject("Spring发送带附件的邮件", "gb2312");

                Multipart mp = new MimeMultipart();

                // 向Multipart添加正文
                MimeBodyPart content = new MimeBodyPart();
                content.setText("内含spring邮件发送的例子,请查收!");

                // 向MimeMessage添加(Multipart代表正文)
                mp.addBodyPart(content);
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                files.add("src/测试.xml");
//                files.add("src/applicationContext-beans.xml");

                // 向Multipart添加附件
                Iterator it = files.iterator();
                while (it.hasNext()) {
                    MimeBodyPart attachFile = new MimeBodyPart();
                    String filename = it.next().toString();
                    FileDataSource fds = new FileDataSource(filename);
                    attachFile.setDataHandler(new DataHandler(fds));
                    attachFile.setFileName("=?utf-8?B?"+enc.encode(fds.getName().getBytes())+"?=");
                    mp.addBodyPart(attachFile);
                }

                files.clear();

                // 向Multipart添加MimeMessage
                mimeMessage.setContent(mp);
                mimeMessage.setSentDate(new Date());
            }
        };

        // 发送带附件的邮件
        sender.send(mimeMail);

        System.out.println("成功发送带附件邮件!");
    }
}



applicationContext-beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host">
			<value>smtp.163.com</value>
		</property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="mail.smtp.timeout">25000</prop>
			</props>
		</property>
		<property name="username">
			<value>邮箱登录名</value>
		</property>
		<property name="password">
			<value>邮箱登录密码</value>
		</property>
	</bean>
    
     <!--要调度的对象-->
	<bean id="springMail" class="com.yan.mail.SpringMail" />

	<!--定义定时执行springMail 这个bean中的sendMail()方法-->
	<bean id="sendMailTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
			<ref bean="springMail" />
		</property>
		<property name="targetMethod">
			<value>sendMail</value>
		</property>
	</bean>

	<!--
		触发器的bean的设置,在这里我们设置了我们要触发的jobDetail是哪个。这里我们定义了要触发的jobDetail是sendMailTask,即触发器去触发哪个bean..并且我们还定义了触发的时间:每天15:40-50pm
	-->
	<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
		<property name="jobDetail">
			<ref bean="sendMailTask" />
		</property>
		<property name="cronExpression">
			<!-- 关键在配置此表达式 -->
			<value>0 40-50 15 * * ?</value>
		</property>
	</bean>

	<!--管理触发器的总设置,管理我们的触发器列表,可以在bean的list中放置多个触发器。-->
	<bean autowire="no"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref local="cronTrigger" />
			</list>
		</property>
	</bean>
</beans>


运行SpringMail,这个程序就会在每天的15:40-15:50每隔一分钟就会发一封邮件到特定的邮箱里

你可能感兴趣的:(spring,bean,xml,quartz,配置管理)