5 Replies Latest reply: Oct 9, 2010 6:38 AM by angelr RSS

    Timer and timer task problem

      hello folks,

      i tried using timer task and timer classes from java.util
      but whenever i set the rate of repeatition to somwhere around a bit more then twice per second i get a latency problem, which means the task is not occuring exactly when it should , mostly its late, and somtimes it happens too fast.
      how can i fix this problem?
      the task is very simple: play a sound.

      also in some mobile phones the timer task is accurate up to higher rates the other phones.

      please help me solve this prolem,
        • 1. Re: Timer and timer task problem

          yes, the timers are not so precise. The most precise solution for this type of task is probably using separate thread. Se start your own thread and manage the timing from within your overriden Thread.run() method. Don't forget to keep sleeping the thread for the rest of the time otherwise you will get a performance problem.

          • 2. Re: Timer and timer task problem
            Cross posted

            • 3. Re: Timer and timer task problem
              Hi Rada

              thanks for replaying
              i tried the additional thread, i got precise timing by that as i remember, but when the second thread was sleeping, i couldnt do anything in the main thread.
              that is , it didnt respond to buttons and listeners in general.

              did i make another thread that worked in a serial way? how do i make it go in parralell to my main thread?
              • 4. Re: Timer and timer task problem
                If you write what you write then you probably didn't create the thread or you are running the code in synchronized methods. The only advice I can give you now is to learn the threads. The java.langThread javadoc should be enough, if not, then uncle Google will definitely help you to find million examples :-)

                • 5. Re: Timer and timer task problem
                  (don't know anything about j2me, but this could help, if available on that platform)

                  Hi, are you using Timer.scheduleAtFixedRate method (instead of schedule)?

                  The javadoc in that method can give you an idea of what's happening.

                  Probably the OS takes a lot of time (millis speaking) to play it (even with a small clip), taking os resources to play, releasing them, etc. Don't destroy the sound object, keep it on memory...

                  Try to change the process priority,as well, or use a shorter sound file.

                  Instead of the sound, test if you have the same problem with Toolkit.getDefaultToolkit().beep()