2 Replies Latest reply: Nov 12, 2007 7:42 AM by 807557 RSS

    java.util.Timer and java.util.TimerTask running threads problem


      I have following scenario.

      +1.+ My thread to send mail has to run once a day at a fixed time thus I am using the following method from the Timer class.

      schedule(TimerTask object, start time, interval)

      +2.+ My thread in the class AppEmailTask that extends TimerTask class reads database and sends mail based on the data received in the run() method.

      +3.+ Whenever I send any mail, I log it into a database table that keeps the record of the emails sent.

      +4.+ I have a stored procedure in the database that supplies me with the data. Cross-checked multiple times, it sends me unique data only everytime.

      Now the Problem:

      I am receiving duplicate mails and also getting duplicate entries into the email log table.

      Is there anything that I am missing in the following that would help me resolve this problem.

      //This method is called only once when the application starts by a servlet
      public void setEmailAlertsTask(int interval)
      int emailAlertTimeInterval = interval;
      EmailAlertTimer = new Timer();
      String timeArr[] = {"1","15","0"};
      Calendar cl = Calendar.getInstance();
      EmailAlertTimer.schedule(new EmailAlertsTask(), cl.getTime(), emailAlertTimeInterval);

      //This is the timer task class
      class EmailAlertsTask extends TimerTask
      public void run()
      ResultSet rs = null;
      CachedRowSet cachedRs = null;
      String subject="";
      String message=(new Date(System.currentTimeMillis())).toString()+"";
      EmailFacade emailBean= new EmailFacadeBean();
      // Fetch Today Alert : Defaut value will be 0
      int alertNum = 1;
      dbConnect = ds.getConnection();
      String generateAlerts = "{call rnr_Alert_TmpAPExpiry(?)}";
      cst = dbConnect.prepareCall(generateAlerts);
      rs = cst.executeQuery();
      cachedRs = new CachedRowSet();
      message=(new Date(System.currentTimeMillis())).toString()+"";
      subject = " Email From Application ";
      message += " Test Email for "+cachedRs.getString("Name")+" ["+cachedRs.getString("empNum")+"];
      emailBean.sendEmail(cachedRs.getString("receiver"),subject,message,cachedRs.getInt("empNum"), cachedRs.getInt("ManagerNum"),cachedRs.getInt("DepartmentNum"),alertNum);
      } catch (SQLException ex) {
      System.out.println(new java.util.Date() + " - Exception occurred in EmailAlertsTask.run()");


      //Email is sent in the standard way as follows:
      public void sendEmail(String emailAddr, String subject, String message, int empNum, int revEmpNum, int jobCodeNum, int alertType)
      String smtpHost = "mySMTPHost";
      String fromAddress = emailAddr;
      java.util.Properties props = new java.util.Properties();
      props.put("mail.smtp.host", smtpHost);
      Session mailSession = Session.getDefaultInstance(props, null);
      InternetAddress fromAddr = new InternetAddress("fromAddress@x.com"); //From address
      InternetAddress toAddr = new InternetAddress(emailAddr);
      // construct a message
      MimeMessage myMessage = new MimeMessage(mailSession);
      String replyToAddress = "replyTo@x.com";
      InternetAddress replyToAddr = new InternetAddress(replyToAddress);
      myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
      myMessage.setSentDate(new java.util.Date());
      // now send the message!
      logEmailToDB(fromAddress, emailAddr, subject, message, empNum, departmentNum, managerNum); //Method to log into the database
      catch (Exception e)
      logger.error("Error occurred in EmailFacadeBean.sendEmail()", e);

      I also checked the email server settings, and I am sure that the email server is not duplicating the emails as there are more than one entry in the email log also.

      But still I am receiving duplicate mails.

      Any help is appreciated.


      Edited by: developing_mind on Nov 8, 2007 5:01 PM
        • 1. Re: java.util.Timer and java.util.TimerTask running threads problem

          Although "time" is certainly an issue in your program, this question is not about real-time Java or the RTSJ. I suggest asking in a more general programming forum - or perhaps something specific to servlets.

          All I can suggest looking at the code is to add tracing/logging information to check if the methods you only except to be called once, are called once. You might also check that the timer is cleaned up when the servlet completes.

          David Holmes
          • 2. Re: java.util.Timer and java.util.TimerTask running threads problem
            Hi David,

            Thanks for the suggestion!! :-)

            I will also post the issue in the servlet forum.

            One thing I would like to make a point that, the servlet is never down until the application is stopped. It is always running in the background. Only the thread which is scheduled to run once everyday is invoked.

            So how do I clear the timer in that case, if that is the possible solution.