美文网首页Java · 成长之路Java学习笔记程序员
Quartz入门(四) --Quartz与Spring结合:定时

Quartz入门(四) --Quartz与Spring结合:定时

作者: 是夏莞也是CiCi | 来源:发表于2017-06-15 16:49 被阅读70次

Quartz入门(四) --Quartz与Spring结合:定时发送邮件

使用Spring项目的Quartz定时任务可以在xml中配置,即写一个Job类来做定时任务实际要完成的任务,但定时功能交给xml文件来配置。

Example:要定时发送邮件

  • 那要写一个Job类来实现发送邮件的任务
  • 任务的触发交给xml文件来配置
  • 最后将此xml文件加入到Spring的applicationContext.xml中就可以啦
发送邮件任务

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * Created by CiCi on 2017/5/9.
 * 发邮件任务
 */
public class SendEmailJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailJob.class);

    EmailInformation emailInformation;
    RedPackageToExcel redPackageToExcelInstance;
    public RedPackageToExcel getRedPackageToExcelInstance() {
        return redPackageToExcelInstance;
    }

    public void setRedPackageToExcelInstance(RedPackageToExcel redPackageToExcelInstance) {
        this.redPackageToExcelInstance = redPackageToExcelInstance;
    }

    public EmailInformation getEmailInformation() {
        return emailInformation;
    }

    public void setEmailInformation(EmailInformation emailInformation) {
        this.emailInformation = emailInformation;
    }

    public void sendMail() {
        try
        {
            final String filePath = emailInformation.getRedPackageAttachLoc() + emailInformation.getAttachName() + ".xlsx";
            String fromMail = emailInformation.getFromMail();
            String toMail = emailInformation.getToMail();
            String user = emailInformation.getUser();
            String password = emailInformation.getPassword();
            String mailTitle = emailInformation.getMailTitle();
            String mailContent = emailInformation.getMailContent();
            String attachName = emailInformation.getAttachName();

            //加载一个配置文件
            Properties props = new Properties();

            // smtp:简单邮件传输协议
            // 设置邮件服务器主机名
            props.put("mail.smtp.host", "smtp.163.com");

            //发送服务器需要通过验证
            props.put("mail.smtp.auth", "true");

            //设置环境信息
            Session session = Session.getInstance(props);//根据属性新建一个邮件会话
            session.setDebug(true); //会打印一些调试信息。

            //由邮件会话新建一个消息对象
            MimeMessage message = new MimeMessage(session);

            //设置邮件内容
            message.setFrom(new InternetAddress(fromMail));//设置发件人的地址
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人,并设置其接收类型为TO
            message.setSubject(mailTitle);//设置标题
            //设置信件内容

            //因为需要加载附件,需要装载多个主体部件
            MimeMultipart partList = new MimeMultipart("mixed");
            message.setContent(partList);

            //创建一个部件
            MimeBodyPart part1 = new MimeBodyPart();
            part1.setText(mailContent);
            partList.addBodyPart(part1);

            //再创建一个部件
            MimeBodyPart part2 = new MimeBodyPart();

            //将原有的export.xlsx删除,重新生成export.xlsx文件并发送
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }

            // 添加附件的内容
            DataSource source = new FileDataSource(filePath);
            part2.setDataHandler(new DataHandler(source));

            //指定附件的名字,使用MimeUtility.encode()对中文进行编码
            SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
            String address = simpleFormat.format(new Date());
            part2.setFileName(MimeUtility.encodeText(attachName + address +".xlsx")); //设置的这个新的名字一定要带有后缀格式啊.xlsx!!!

            partList.addBodyPart(part2);

            //发送邮件
            Transport transport = session.getTransport("smtp");
            transport.connect(user, password);
            transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
            transport.close(); //这个最好放到finally中哎
        }catch (Exception e) {
            LOGGER.error("sendEmail failed" + e);
        }
    }

    public void execute(){
        try {
            sendMail();
        } catch (Exception e) {
            LOGGER.error("autosendEmail failed" + e);
        }

    }
}

XMLl文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--定时发送邮件-->
    <bean id="sendEmailJob" class="com.xiaomi.cashpay.statistics.autosendstatistics.SendEmail.SendEmailJob"></bean>
    <bean id="job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="sendEmailJob" />
        <property name="targetMethod" value="execute" />
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="job" />
        <!--<property name="cronExpression" value="0 0 9 * * ?" />-->
        <property name="cronExpression" value="0 * * * * ?" />
    </bean>

    <bean id="scheduler" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            </list>
        </property>
        <property name="autoStartup" value="true" />
    </bean>
</beans>
将quartz-config.xml文件引入到applicationContext.xml中

<import resource="classpath*:/quartz-config.xml" />

酱紫就可以了~ 定时发送邮件新技能Get~

That's all. Thank U~

相关文章

网友评论

    本文标题:Quartz入门(四) --Quartz与Spring结合:定时

    本文链接:https://www.haomeiwen.com/subject/jbluqxtx.html