I have been tasked to create an application that will send an email to a selection of recipients once every (n) minutes. The application in which this resides is structured in a way that it will reset itself by calling back to <classname>.main(args)
whenever it is needed. My problem is, when I call to <classname>.emailSending
, the application fires off 2 emails to each user immediately. The application does need to send an email at runtime, but it is only required to send a single email to each recipient.
Does anyone have any suggestions?
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;
}
}
You should look at Executors.newSingleThreadScheduledExecutor
(http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadScheduledExecutor()). This is designed to do exactly what you want.
ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
scheduledExecutor.schedule(new Runnable() {
@Override
public void run() {
/*
send email
*/
}
}, n, TimeUnit.MINUTES);
The runnable will execute every n minutes. If you want to stop the system, just send the shutdown
command to the scheduledExecutor
.