7 Replies Latest reply: Jan 18, 2008 6:47 AM by 791266 RSS

    Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days

    807603
      We have an application which downloads mails from GroupWise Server. We have implemented with SwingWorker abstract class(java.sun.com/products/jfc/tsc/articles/threads/src/SwingWorker.java) and thread pool. Thread pool will download mails from user MailBox. Same time more than one user mails can be down loaded based on no. of threads define in thread pool. SwingWorker invokes this thread pool.

      On top of this I have implemented a Timer to Schedule this process once in a day at a particular time. I used Timer.ScheduleAtFixedRate(Timer t,Date d,Long l). I set to run at every day at 5.30PM. I am starting SwingWorker thread inside this timer task method. It runs perfectly for first three days. Fourth day it runs twice. That is after one round of mail download is over for all user and after few minutes it downloads one more time. Next three days fine. It will run only once 5.30Pm and again 4th day same problem.
      Can any one help to find what could be the probem?
      Here is the timer code.

      String dailyFreq = options.getSchedularTime();
      processTimer = new Timer(true);//java.util timer class
      Date startDate = getDailyFreq();
      ScheduledProcess scheduledProcess = new ScheduledProcess(iia_DefaultMutableTreeNodeProcessorHandle, iia_frame, pool, startDate);
      processTimer.scheduleAtFixedRate(scheduledProcess, startDate , 1000 * 60 * 60 * 24);
      -----------------------------------------------------------------------------------------------------------------------------
      ScheduledProcess.java
      import java.util.Calendar;
      import java.util.Date;
      import java.util.TimerTask;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      import com.computhink.iia.Constants;
      import com.computhink.iia.logging.VWLogger;
      import com.computhink.iia.options.IAAGeneralOptions;
      import com.computhink.iia.ui.util.SwingWorker;
      import com.computhink.iia.ui.util.ThreadPool;

      class ScheduledProcess extends TimerTask {

           private static Logger logger = Logger.getLogger("com.computhink.iia");
           private ThreadPool tempPool;
           IIA_JFrame iia_frm = null;
           IIA_DefaultMutableTreeNodeProcessor iia_DefaultMutableTreeNodeProcessorHdle = null;
           Date startDate = null;
           private static int count = 0;

           public ScheduledProcess(IIA_DefaultMutableTreeNodeProcessor iia_DefaultMutableTreeNodeProcessorHandle,
                     IIA_JFrame iia_frame, ThreadPool pool, Date startDate){
                this.iia_DefaultMutableTreeNodeProcessorHdle = iia_DefaultMutableTreeNodeProcessorHandle;
                this.tempPool = pool;
                this.iia_frm = iia_frame;
                this.startDate = startDate;
           }
           public void doScheduledProcess(){
                SwingWorker worker = new SwingWorker() {
           public Object construct() {
                          Calendar calendar = Calendar.getInstance();
                          calendar.setTime(startDate);
                          int addDays = 1;
                while (!Constants.stopFlag ) {
                Date now = Calendar.getInstance().getTime();
      // This method 'pollFoldersAndFiles' calls a recursive method 'polls' which downloads mails
      // from each folders(Inbox , Sent Items) of each user.
                iia_DefaultMutableTreeNodeProcessorHdle.pollFoldersAndFiles(iia_frm.firstTreeNode,tempPool);
                try {
                long snooze = 1000 * 60 * 60 * 24;
                Calendar calendarNow = Calendar.getInstance();
                          snooze = 1000 * 60 * 60 * 24 - (calendarNow.getTimeInMillis() - now.getTime());
                if(now.after(startDate)&& count == 0)
                     {
                     count = 1;
                          snooze = 1000 * 60 * 60 * 24 - (now.getTime()-startDate.getTime());
                     }
                calendar.add(calendar.DATE, addDays);
           if(!Constants.stopFlag)
                IIA_JFrame.statusInformation.setText("Status: Next polling will start at: "+calendar.getTime().toString());
      // Here I am making this Swing Worker thread to sleep for 24 hours for daily schedule. The third param in 'scheduleAtFixedRate' didn't help
      // me to stop after one round of poll.
           Thread.currentThread().sleep(snooze);
                     }catch (InterruptedException exception){
           VWLogger.log(Level.SEVERE, "Exception", exception);
           }
           addDays++;

           }
           Constants.stopFlag = false; //set stop to false
           return null;
           }
           public void finished() {
                tempPool.stopRequestAllWorkers();
                IIA_Monitor.processTimer.cancel();
      try{
           Thread.currentThread().interrupt();
           tempPool = null;
      }catch(Exception ex){

      }
                iia_frm.statusInformation.setText("Status: ");
           }
                };
                worker.start();
                if(Constants.stopFlag){
                     //Should cancel the timer here
                     IIA_Monitor.processTimer.cancel();
                     worker.interrupt();
                }
           }
           public void run(){
                doScheduledProcess();
           }
      }
        • 1. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
          807603
          Hi all,

          Please any one guide me where it is going wrong. I will paste again my code with format

          Thanks In advance

          Here is the timer code.
          String dailyFreq = options.getSchedularTime();
          processTimer = new Timer(true);//java.util timer class 
          Date startDate = getDailyFreq();
          ScheduledProcess scheduledProcess = new ScheduledProcess(iia_DefaultMutableTreeNodeProcessorHandle, iia_frame, pool, startDate);
          processTimer.scheduleAtFixedRate(scheduledProcess, startDate , 1000 * 60 * 60 * 24);
          ScheduledProcess.java
          import java.util.Calendar;
          import java.util.Date;
          import java.util.TimerTask;
          import java.util.logging.Level;
          import java.util.logging.Logger;
          import com.computhink.iia.Constants;
          import com.computhink.iia.logging.VWLogger;
          import com.computhink.iia.options.IAAGeneralOptions;
          import com.computhink.iia.ui.util.SwingWorker;
          import com.computhink.iia.ui.util.ThreadPool;
          
          class ScheduledProcess extends TimerTask {
          
           private static Logger logger = Logger.getLogger("com.computhink.iia");
           private ThreadPool tempPool;
           IIA_JFrame iia_frm = null;
           IIA_DefaultMutableTreeNodeProcessor iia_DefaultMutableTreeNodeProcessorHdle = null;
           Date startDate = null;
           private static int count = 0;
          
           public ScheduledProcess(IIA_DefaultMutableTreeNodeProcessor    iia_DefaultMutableTreeNodeProcessorHandle,
           IIA_JFrame iia_frame, ThreadPool pool, Date startDate){
           this.iia_DefaultMutableTreeNodeProcessorHdle =   iia_DefaultMutableTreeNodeProcessorHandle;
           this.tempPool = pool;
           this.iia_frm = iia_frame;
           this.startDate = startDate;
          }
          public void doScheduledProcess(){
           SwingWorker worker = new SwingWorker() {
           public Object construct() {
           Calendar calendar = Calendar.getInstance();
           calendar.setTime(startDate);
           int addDays = 1;
           while (!Constants.stopFlag ) {
           Date now = Calendar.getInstance().getTime();
           // This method 'pollFoldersAndFiles' calls a recursive method 'polls' which downloads mails
           // from each folders(Inbox , Sent Items) of each user.
           iia_DefaultMutableTreeNodeProcessorHdle.pollFoldersAndFiles   (iia_frm.firstTreeNode,tempPool);
           try {
            long snooze = 1000 * 60 * 60 * 24;
            Calendar calendarNow = Calendar.getInstance();
            snooze = 1000 * 60 * 60 * 24 - (calendarNow.getTimeInMillis() - now.getTime());
            if(now.after(startDate)&& count == 0)
            {
             count = 1;
             snooze = 1000 * 60 * 60 * 24 - (now.getTime()-startDate.getTime());
           }
           calendar.add(calendar.DATE, addDays);
           if(!Constants.stopFlag)
             IIA_JFrame.statusInformation.setText("Status: Next polling will start at: "
             +calendar.getTime ().toString());
           // Here I am making this Swing Worker thread to sleep for 24 hours for daily schedule. 
           //The  third param in 'scheduleAtFixedRate' didn't help
           // me to stop after one round of poll.
              Thread.currentThread().sleep(snooze);
           }catch (InterruptedException exception){
           VWLogger.log(Level.SEVERE, "Exception", exception);
          }
          addDays++;
          
          }
          Constants.stopFlag = false; //set stop to false
          return null;
          }
          public void finished() {
           tempPool.stopRequestAllWorkers();
           IIA_Monitor.processTimer.cancel();
           try{
            Thread.currentThread().interrupt();
            tempPool = null;
            }catch(Exception ex){
          
          }
          iia_frm.statusInformation.setText("Status: ");
          }
          };
          worker.start();
          if(Constants.stopFlag){
          //Should cancel the timer here
          IIA_Monitor.processTimer.cancel();
          worker.interrupt();
          }
          }
           public void run(){
            doScheduledProcess();
           }
          }
          • 2. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
            807603
            check this http://bugs.sun.com/view_bug.do?bug_id=4290274
            • 3. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
              807603
              Hi Sujikin,

              This is link full to understand some more information about Timer - Schedule. But here I am not changing System time and it is perfectly running for first fewdays and then it is doing that task twice in one day and again next few days running correctly.

              Since I am using too many thread concept some where it is going wrong? (Timer, Swing worker, Thread pool)

              Thanks in Advance
              • 4. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
                791266
                A Timer is single threaded and you should never call sleep on that thread. You might make it miss one execution since you are causing it to sleep and it will try to catch up after that. That's probably what you are seeing.

                Kaj
                • 5. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
                  807603
                  Hi Kaj,

                  What you are saying is correct. Logically I suppose not to use thread sleep when I am using Period in ScheduleAtFixedRate method. But if I comment that line it is not stopping after one completion. So I added sleep.
                  Before, I blindly made current thread to sleep. But Now I added like this. I have set thread name as 'SwingWorker' in SwingWorker.java. Getting that thread and making it to sleep.
                  And in ScheduledProcess.java I have changed the code like this still the result is same.
                  if(!Constants.stopFlag)
                  IIA_JFrame.statusInformation.setText("Status:  Next polling will start at: "
                                 +calendar.getTime().toString());
                                     Map threadMap = Thread.currentThread().getAllStackTraces();
                                      Set set = threadMap.keySet();
                               Iterator i = set.iterator();
                                  while(i.hasNext()){
                                       Thread t = (Thread)i.next();
                                        VWLogger.info("thread name "+t.getName());
                                        if(t.getName().trim().equalsIgnoreCase("SwingWorker".trim())){
                                         VWLogger.info("SwingWorker going to sleep");
                                         t.sleep(snooze);
                                 }
                                  }
                                  //Thread.currentThread().sleep(snooze);
                  Thanks in Advance
                  • 6. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
                    791266
                    The sleep method is static and will always cause the current thread to sleep. You aren't making the other thread sleep.

                    (And your logic is probably way off if you need to make that thread sleep)
                    • 7. Re: Timer.ScheduleAtFixedRate(Timer t,Date d,Long l) is failing after 3days
                      791266
                      Btw. Remove the loop. The Timer is the loop.