安排TimerTask运行一次

时间:2015-03-10 15:05:50

标签: java multithreading jdbc javamail

我的任务是创建一个应用程序,每隔(n)分钟就会向一组收件人发送一封电子邮件。它所在的应用程序的结构是通过在需要时回调<classname>.main(args)来重置自身。我的问题是,当我呼叫<classname>.emailSending时,应用程序会立即向每个用户发送2封电子邮件。应用程序确实需要在运行时发送电子邮件,但只需要向每个收件人发送一封电子邮件。

有人有任何建议吗?

package database_administration;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

class EmailSending extends TimerTask
{
    public static FileInputStream propFile;
    static Connection conn = null;
    static Statement query = null;
    static String path;
    static Statement stmnt;
    public void run()
    {
        try
        {
            Date date = new Date();     
            SimpleDateFormat mailDate = new SimpleDateFormat();
            mailDate = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
            String mail = mailDate.format(date);
            propFile = new FileInputStream("config.ini");
            Properties config = new Properties(System.getProperties()); 
            config.load(propFile);
            String host = config.getProperty("host");
            String port = config.getProperty("port");
            path = config.getProperty("path");
            String DB_URL = config.getProperty("DB_URL");
            String USER = config.getProperty("USER");
            String PASS = config.getProperty("PASS");
            path = config.getProperty("path");
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            String sender = config.getProperty("sender");
            Properties toRecipients = System.getProperties();
            Session current = Session.getDefaultInstance(toRecipients);
            toRecipients.setProperty("mail.smtp.host", host);
            toRecipients.setProperty("mail.smtp.port", port);
            MimeMessage message = new MimeMessage(current);
            message.setFrom(new InternetAddress(sender));
            String[] recipients = config.getProperty("EmailList").split(";");
            for(int i=0;i<recipients.length;i++)
            {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i].trim()));
                message.setSubject("Results of Audit Trail "+mail);
                message.setText(messageBody().toString());
                Transport.send(message);
            }
        }
        catch (MessagingException me)
        {
            System.out.println(me.getMessage());
        }
        catch (FileNotFoundException fnf)
        {
            System.out.println(fnf.getMessage());
        }
        catch (IOException ioe)
        {
            System.out.println(ioe.getMessage());
        }
        catch (SQLException sqle)
        {
            System.out.println(sqle.getMessage());
        }
        catch (ClassNotFoundException cnf)
        {
            System.out.println(cnf.getMessage());
        }
    }
    public static void emailSend(int control) throws IOException
    {
        Timer timer = new Timer();
        timer.schedule(new EmailSending(), 0, control*60000);
    }
    private static StringBuilder messageBody() throws SQLException
    {
        stmnt = conn.createStatement();
        String SQL = "Select Action from Java_Test_AuditTrail";
        ResultSet rs1 = stmnt.executeQuery(SQL);
        rs1.last();
        int rowNumb = rs1.getRow();
        int list = 0;
        int delete = 0;
        int update = 0;
        int load = 0;
        int upload = 0;
        int display = 0;
        int add = 0;
        rs1.beforeFirst();
        rs1.next();
        int seeker=1;
        while(rs1.next()&&seeker<=rowNumb)
        {
            String actExecuted = rs1.getString("Action");
            if(actExecuted.equals("LIST"))
            {
                list++;
            }
            if(actExecuted.equals("DELETE"))
            {
                delete++;
            }
            if(actExecuted.equals("UPDATE"))
            {
                update++;
            }
            if(actExecuted.equals("RE-LOAD"))
            {
                load++;
            }
            if(actExecuted.equals("UPLOAD"))
            {
                upload++;
            }
            if(actExecuted.equals("DISPLAY AUDIT"))
            {
                display++;
            }
            if(actExecuted.equals("USER_CREATED"))
            {
                add++;
            }               
        }
        StringBuilder builder = new StringBuilder();
        builder.append("Since Creation of the database, there have been: ["+list+"] List requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+delete+"] Delete requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+update+"] Update requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+load+"] Re-load requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+upload+"] Upload requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+display+"] Audit-Display requests executed"+"\n");
        builder.append("\n");
        builder.append("Since Creation of the database, there have been: ["+add+"] User-Creation requests executed"+"\n");
        return builder;
    }   
}

1 个答案:

答案 0 :(得分:4)

您应该查看Executors.newSingleThreadScheduledExecutorhttp://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadScheduledExecutor())。这是为了完全按照你想要的那样做的。

ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
scheduledExecutor.schedule(new Runnable() {
    @Override
    public void run() {
        /*
        send email
        */
    }
}, n, TimeUnit.MINUTES);

runnable将每n分钟执行一次。如果要停止系统,只需将shutdown命令发送到scheduledExecutor