如何在Simple Quartz Schedular中安排时间间隔

时间:2015-10-14 06:29:34

标签: java quartz-scheduler

我第一次使用Quartz调度程序,而我正在使用Crown Trigger来完成我的工作。我的代码如下:

SchedulerJob.java

package com.controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SchedulerJob implements Job {

    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        System.out.println("welcome to scheduler");
        Statement stmt = null;
        String url = "jdbc:mysql://localhost:3306/marketing_database";
        Connection con = null;
        ResultSet rs = null;

        // get current date time with Calendar()
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        String systemDate = dateFormat.format(cal.getTime());

        //mail Server properties
//      
//      String host = "smtp.gmail.com";
//      Properties props = new Properties();
//      props.put("mail.smtp.auth", "true");
//      props.put("mail.smtp.starttls.enable", "true");
//      props.put("mail.smtp.host", host);
//      props.put("mail.smtp.port", "587");
//
//      String from = "southstartechnology.com";// change accordingly
//      final String username = "info@southstartechnology.com";// change accordingly
//                                                          
//      final String password1 = "South@123";// change accordingly
//      Session session1 = Session.getInstance(props,
//              new javax.mail.Authenticator() {
//                  protected PasswordAuthentication getPasswordAuthentication() {
//                      return new PasswordAuthentication(username, password1);
//                  }
//              });
//
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(url, "root", "root");
            stmt = con.createStatement();
            String sql = "select * from marketing_database.purchase where PaymentDate='"+systemDate+"';";
            rs = stmt.executeQuery(sql);
            ArrayList<String> list = new ArrayList<String>();
            String emailIdStr, item, grandTotal,vendorAddress;
            Date purchaseDate, paymentDate;
            while (rs.next()) {
                emailIdStr = rs.getString("email");
                item = rs.getString("Item");
                purchaseDate = rs.getDate("Date");
                grandTotal = rs.getString("GrandTotal");
                vendorAddress = rs.getString("VendorAddress");
                paymentDate = rs.getDate("PaymentDate");
                System.out.println("Email is===" + emailIdStr);
                System.out.println("purchaseDate is===" + purchaseDate);
                System.out.println("grandTotal is===" + grandTotal);
                System.out.println("vendorAddress is===" + vendorAddress);
                System.out.println("paymentDate is===" + paymentDate);
                String mailTo = emailIdStr;// change accordingly
                    // Sender's email ID needs to be mentioned

                // Assuming you are sending email through relay.jangosmtp.net

                // Get the Session object.

//              try {
//                  // Create a default MimeMessage object.
//                  Message message = new MimeMessage(session1);
//
//                  // Set From: header field of the header.
//                  message.setFrom(new InternetAddress(from));
//
//                  // Set To: header field of the header.
//                  message.setRecipients(Message.RecipientType.TO,
//                          InternetAddress.parse(to));
//
//                  // Set Subject: header field
//                  message.setSubject("Purchase Due payment");
//
//                  // Now set the actual message
//                  // message.setText("Hello, this is your Password \n dfggghlkgh: "
//                  // + password);
//                  message.setText("Dear " + emailIdStr
//                          + " You are welcome in messaging service!!! ");
//                  // Send message
//
//                  Transport.send(message);
//                  System.out.println("Message Sent successfully!!");
//
//              } catch (MessagingException e) {
//                  throw new RuntimeException(e);
//              }
//
//          }
//      }
//

        String host = "smtp.gmail.com";
        String port = "587";
        String mailFrom = "info@southstartechnology.com";
        String password = "South@123";

        // outgoing message information
        //String mailTo = +emailIdStr;
        String subject = "Due Payment";

        // message contains HTML markups
        String message = "<i>Greetings!</i><br>";
        message += "<b>Wish you a nice day!</b><br>";
        message += "<font color=red>Arvind</font>";
        String message1 ="<b>Hi sir! Greetings for the day,</b><br>";
        message1+="<i>Following payment are due as on today,please arrange for the payment.<i><br>";
        message1+= "<html><head><style>table, th, td { border: 1px solid black;border-collapse: collapse}th, td { padding: 5px;}</style></head><body>";
        message1+="<table ><tr><th>Item</th><th>Purchase Date</th><th>TotalAmount</th><th>VendorAddress</th><th>Payment Date</th></tr>";
        message1+="<tr><td>"+item;
        message1+="</td>";
        message1+="<td>"+purchaseDate;
        message1+="</td>";
        message1+="<td>"+grandTotal;
        message1+="</td>";
        message1+="<td>"+vendorAddress;
        message1+="</td>";
        message1+="<td>"+paymentDate;
        message1+="</td></tr>";
//      message1+=" <tr><td></td><td>10-12-2015</td><td>50000</td><td>Electronic City</td><td>03-09-2015</td></tr>";
        message1+="</table></body></html>";
        SchedulerJob mailer = new SchedulerJob();

        try {
            mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
                    subject, message1);
            System.out.println("Email sent.");
        } catch (Exception ex) {
            System.out.println("Failed to sent email.");
            ex.printStackTrace();
        }

            }
        }
        catch (Exception ex) {
        ex.printStackTrace();
    }


    }
    public void sendHtmlEmail(String host, String port, final String userName,
            final String password, String toAddress, String subject,
            String message) throws AddressException, MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        Message msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        // set plain text message
        msg.setContent(message, "text/html");

        // sends the e-mail
        Transport.send(msg);

    }

}

QuartzSchedulerListener.java

package com.controller;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.controller.SchedulerJob;

public class QuartzSchedulerListener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent arg0) {
        //
    }

    public void contextInitialized(ServletContextEvent arg0) {

        JobDetail job = JobBuilder.newJob(SchedulerJob.class)
                .withIdentity("anyJobName", "group1").build();

        try {

            Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("anyTriggerName", "group1")
                    .withSchedule(
                            CronScheduleBuilder.cronSchedule("0 0 12 * * ?"))
                    .build();

            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();
            scheduler.scheduleJob(job, trigger);

        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }
}

我正在尝试安排触发器以24小时间隔执行作业但无法执行此操作。所以请解决我的问题。

2 个答案:

答案 0 :(得分:1)

对于Job Type Cron,它可以完美

Trigger trigger = TriggerBuilder
                    .newTrigger()
                    .withIdentity("anyTriggerName", "group1")
                    .withSchedule(
                            CronScheduleBuilder.cronSchedule("0 0 23 * * ?"))
                    .build();

答案 1 :(得分:0)

像这样:

     Trigger trigger = newTrigger() 
         .withIdentity(triggerKey("myTrigger", "myTriggerGroup"))
         .withSchedule(SimpleScheduleBuilder.simpleSchedule()
             .withIntervalInHours(24)
             .repeatForever())
         .startNow()
         .build();

请参阅:http://quartz-scheduler.org/api/2.2.0/org/quartz/TriggerBuilder.html