Search code examples
javaemailbackground-process

how to send mail in background right after insert data in db through method in java


Sending Mail in Java making me to wait on page for long time until all mails finish sending.

I'm inserting data's into DB from daoImpl class file method. after inserting im sending emails in same method.

how i can apart only the mail process to background and return to action layer after insert data.

public int insertViewInfoDetails(AddViewInfoForm form) throws SQLException, Exception {

   //DATABASE INSERT CODE...
    pst.setDouble(29, RE_ORDER_LEVEL);
    pst.execute();
    Logger.getLogger(CLASS_NAME).info("inserted ViewTankInfoDetails - " + form);

    StringBuilder emailDesc = new StringBuilder();
    emailDesc.append("Customer  :: ");
    emailDesc.append(CUSTOMER_NAME);
    emailDesc.append("\n");

    final String getEmailId = "SELECT email_id FROM mst_user";
    pst = conn.prepareStatement(getEmailId);
    pst.setString(1, CONTAINER_ID);
    rs5 = pst.executeQuery();
    while (rs5.next()) {
        //CALL MAILING METHOD
        eMailAfterGettingAlerts(properties, rs5.getString("EMAIL_ID"), emailDesc.toString());
    }
    rs5.close();
    rs5 = null;

return n:
}

can i create Scheduler? not by timing... but only when i call it should run after that process should stop.


Solution

  • You can execute it in another thread, set the mailing logic in implementation for a runnable interface and while you loop through the results use thread executor to execute the sending mail logic

    Sample for the runnable :

    class MailSender implements Runnable {
        public MailSender(String email,String message) {
            this.email=email;
            this.message=message;
        }
    
        @Override
        public void run() {
            sendMail(email,message)
        }
    }
    

    and you can run it using the executor service

    ExecutorService executorService = Executors.newCachedThreadPool();
    while (rs5.next()) {
          executorService.submit(new MailSender(rs5.getString("EMAIL_ID"),rs5.getString("EMAIL_MESSAGE")));
    }