Quartz是一个开源的作业调度框架,它完全由Java写成,并设计用于J2SE和J2EE应用中。下面介绍在J2SE中应用的邮件发送工作调度程序.
           Quartz要运行起来,最简单需要1. ***Job  自己实现的工作类 ;2. ***Quartz 调度你实现的工作类.
           一. 
***Job.java 实现Quartz框架的Job接口.
/**
 *
 * Title:     发送邮件工作类  
 * Copyright:    Copyright (c) 2006
 * Company:      stone
 * @author:     yangstone
 * @version 1.0
 */
package org.yq.myQuartz.jobs;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.yq.myQuartz.utils.MailJobUtil;

/**
 * @ MailJob.java
 * 描述:
 * @author yangstone 
 * 创建日期:2006-3-18
 * @version bookstore 1.0
 * 杨强 [stone] 版权所有
 */
public class MailJob implements Job{

    private static Log _log = LogFactory.getLog(MailJob.class);
   
    public static final String FROMMAIL = "fromMail";
    public static final String TOMAIL = "toMail";
    public static final String CONTENT = "content";
    public static final String SUBJECT = "subject";

    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap data = context.getJobDetail().getJobDataMap();
        MailJobUtil.sendMail(data.getString(FROMMAIL),
                data.getString(TOMAIL), data.getString(CONTENT), data.getString(SUBJECT));
       
    }

}
       二.  ***Quartz.java 调度自己实现的Job类,主要是通过Quartz中的触发器用来告诉调度程序作业什么时候触发.    
/**
 *
 * Title:     执行工作类
 * Copyright:    Copyright (c) 2006
 * Company:      stone
 * @author:     yangstone
 * @version 1.0
 */
package org.yq.myQuartz.execute;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.yq.myQuartz.jobs.MailJob;

/**
 * @ myEmailQuartz.java
 * 描述:
 * @author yangstone 
 * 创建日期:2006-3-18
 * @version bookstore 1.0
 * 杨强 [stone] 版权所有
 */
public class myEmailQuartz {

    public void run() throws Exception {
        Log log = LogFactory.getLog(myEmailQuartz.class);

        log.info("------- Initializing -------------------");

        // First we must get a reference to a scheduler
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();

        log.info("------- Initialization Complete --------");

        log.info("------- Scheduling Jobs ----------------");

        JobDetail job1 = new JobDetail("job1", "group1", MailJob.class);
       
        Trigger trigger = TriggerUtils.makeDailyTrigger(23, 00); //每日 23:00触发工作执行
        trigger.setName("trigger1");
        trigger.setGroup("group1");
        trigger.setJobName("job1");
        trigger.setJobGroup("group1");

        // pass initialization parameters into the job
        job1.getJobDataMap().put(MailJob.FROMMAIL, "*****");
        job1.getJobDataMap().put(MailJob.TOMAIL, "*****");
        job1.getJobDataMap().put(MailJob.CONTENT, "*****");
        job1.getJobDataMap().put(MailJob.SUBJECT, "*****");
       
        // schedule the job to run
        Date scheduleTime1 = sched.scheduleJob(job1, trigger);
        log.info(job1.getFullName() +
                " will run at: " + scheduleTime1);
        log.info(job1.getFullName() +
                " will run at: " + scheduleTime1 );



        log.info("------- Starting Scheduler ----------------");

        // All of the jobs have been added to the scheduler, but none of the jobs
        // will run until the scheduler has been started
        sched.start();

        log.info("------- Started Scheduler -----------------");
       
        log.info("------- Waiting 60 seconds... -------------");
        try {
            // wait five minutes to show jobs
            Thread.sleep(60L * 1000L);
            // executing...
        } catch (Exception e) {
        }

        log.info("------- Shutting Down ---------------------");

        sched.shutdown(true);

        log.info("------- Shutdown Complete -----------------");

        SchedulerMetaData metaData = sched.getMetaData();
        log.info("Executed " + metaData.numJobsExecuted() + " jobs.");

    }

    public static void main(String[] args) throws Exception {

        myEmailQuartz example = new myEmailQuartz();
        example.run();
    }
}
       
        至此,一个简单的应用Quartz进行日发送邮件的程序已经完成.
         以下是发送邮件的简单实现程序:
/**
 *
 * Title:    发送邮件类      
 * Copyright:    Copyright (c) 2006
 * Company:      stone
 * @author:     yangstone
 * @version    1.0
 */
package org.yq.myQuartz.utils;

import java.util.Date;
import java.util.Properties;

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

/**
 * @ SendMail.java
 * 描述:
 * @author yangstone 
 * 创建日期:2006-3-18
 * @version bookstore 1.0
 * 杨强 [stone] 版权所有
 */
public class SendMail {
    private String tomail;
      private String frommail;
      private String subject;
      private String content;
      private String imagecard;
      String smtp="smtp.*****.com";//设置邮件服务器

      public SendMail() {
      }
      public String getTomail() {
        return tomail;
      }
      public void setTomail(String tomail) {
        this.tomail = tomail;
      }
      public String getFrommail() {
        return frommail;
      }
      public void setFrommail(String frommail) {
        this.frommail = frommail;
      }
      public String getSubject() {
        return subject;
      }
      public void setSubject(String subject) {
        this.subject = subject;
      }
      public String getContent() {
        return content;
      }
      public void setContent(String content) {
        this.content = content;
      }
      public String getImagecard() {
        return imagecard;
      }
      public void setImagecard(String imagecard) {
        this.imagecard = imagecard;
      }

      /**
       *
      * 描述:发送邮件
      * @return true:发送成功 false:发送失败
      * @author{user}
      * 创建时间:2006-3-19
       */
      public boolean sendMail(){
       try{
         Properties p=System.getProperties();
         p.put("mail.smtp.host",this.smtp);
         p.put("mail.smtp.auth","true");  //设置为须验证的模式
        
         Authenticator auth = new Email_ca("邮箱用户名","密码");
         Session session=Session.getDefaultInstance(p, auth);
         MimeMessage msg=new MimeMessage(session);
         msg.setSentDate(new Date());
         InternetAddress from=new InternetAddress(frommail);
         msg.setFrom(from);
         InternetAddress[] address = {
             new InternetAddress(tomail)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(this.subject); //设置邮件主题
         msg.setText(this.content); //设置邮件内容
         Transport.send(msg);
         return true;
       }catch(AddressException addr_e){
         System.out.println(addr_e.getMessage());
         return false;
       }catch(MessagingException msg_e){
         System.out.println(msg_e.getMessage());
         return false;
       }
    }
}


/**
 *
 * Title:      邮箱身份认证类
 * Copyright:    Copyright (c) 2006
 * Company:      stone
 * @author:     yangstone
 * @version 1.0
 */
package org.yq.myQuartz.utils;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * @ Email_ca.java
 * 描述:
 * @author yangstone 
 * 创建日期:2006-3-18
 * @version bookstore 1.0
 * 杨强 [stone] 版权所有
 */
public class Email_ca extends Authenticator{
    private String user=null;
      private String pwd=null;
      public Email_ca(){
        super();
      }
      public void setUser(String user){
        this.user=user;
      }
      public void setPwd(String pwd){
        this.pwd=pwd;
      }
      public Email_ca(String user,String pwd){
        super();
        setUser(user);
        setPwd(pwd);
      }
      public PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(user,pwd);
      }
}


/**
 *
 * Title:      邮件发送工具类
 * Copyright:    Copyright (c) 2006
 * Company:      stone
 * @author:     yangstone
 * @version 1.0
 */
package org.yq.myQuartz.utils;

/**
 * @ MailJob.java
 * 描述: 用于QUARTZ调用的门面
 * @author yangstone 
 * 创建日期:2006-3-18
 * @version bookstore 1.0
 * 杨强 [stone] 版权所有
 */
public class MailJobUtil {
   
    /**
     *
    * 描述:
    * @param fromMail 发送邮箱
    * @param toMail 送至邮箱
    * @param content 邮件内容
    * @param subject 邮件主题
    * @author yangstone
    * 创建时间:2006-3-19
     */
    public static void sendMail(String fromMail, String toMail, String content, String subject){
        SendMail se = new SendMail();
        se.setFrommail(fromMail);
        se.setTomail(toMail);
        se.setContent(content);
        se.setSubject(subject);
        se.sendMail();
    }
}

log4j.xml 配置日志输出格式

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="default" class="org.apache.log4j.ConsoleAppender">
    <param name="target" value="System.out"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="[%p] %d{dd MMM hh:mm:ss.SSS aa} %t [%c]%n%m%n%n"/>
    </layout>
  </appender>


 <logger name="org.quartz">
   <level value="debug" />
 </logger>

  <root>
    <level value="debug" />
    <appender-ref ref="default" />
  </root>

 
</log4j:configuration>

                上面这个邮件发送程序非常实用,很多系统都应该可以用到,要应用于WEB应用需要改动的地方也不多.希望大家试试改造一番,用于自己的网站,不过很多网站已经有这样的应用了,哈哈!

posted on 2007-10-31 10:31  冷火  阅读(806)  评论(0编辑  收藏  举报