NullPointerExceotion on Timer.cancel

Hi everyone!
I'm a bit messed up with a rebellious timer in my program.
It is supposed to measure a timeout between a messege sent by a server and a response from a client. Everything runs in UDP.
So, the server sends a keepalive message periodically by executing this method (called from another timerTask):
public void sendKeepalive() {
          Message message = new Message("KPA","",this, this);         // Message is a class used for wrapping messages in the server
          tx(message);                                                                       // Sends a message over a UDP socket
          waitForACK = new Timer();                                           
          waitForACK.schedule(new WaitForACKTask(this), keepaliveTimeout);
}AFAIK, this code works fine, because the timer task works fine, and it does diisconnect the client once the time is up. This is the code to WaitForACKTask:
public class waitForACKTask extends TimerTask {
     private Client client;                            // Client is a class that deals with one client (it is part of the server; ie: the server has one Client class per connected client)
     public WaitForACKTask(Client client){
          this.client = client;
     public void run(){
          client.disconnect();    //deletes the user from the server list and notifies it that it has been disconnected
}Again, this seems to work fine.
Now, the problem comes when the client answers the petition. It sends an "ACK" message, wich is processed as follows:
     public void process(Message message) {
          if (message.returnType().equals("ACK")){              
               System.out.println("ACK received");                  // I have tested that it does recognize the type of the message correctly
               waitForACK.cancel();                                       // This is the line where NullPointerException is launched
          } else if (message.returnType().equals("DIS")){
               disconnect();
          else {
               control.queue(message);                 
     }So, here is where the code fails; on waitForACK.cancel():
java.lang.NullPointerException
     at chatServer.Client.process(Client.java:72)
     at chatServer.ListenClient.run(ListenClient.java:29)After that, te timer simply keeps on counting (as if no ACK has been received) and disconnects the client after timeout.
I've looked up in the java documentation and Timer.cancel() is not supposed to launch any exceptions.
Thank's in advance!

Just figured it out by myself! I had tested everything with a fake client (that is, me writing the protocol messages on a dumb client made just by a window and a socket), and I saw it didn't fail. So it turns out that the ACK was received before the timer had had time to be created. It didn't fail when I was the client, because I was much slower. So everything is fixed by changing the order in the code of sendKeepAlive:
public void sendKeepalive() {
                waitForACK = new Timer();                                           
          waitForACK.schedule(new WaitForACKTask(this), keepaliveTimeout);
          Message message = new Message("KPA","",this, this);       
          tx(message);                                                                   
}Edited by: fenom_ on May 16, 2009 8:50 AM

Similar Messages

  • Long time cancel process

    Hello expert,
    I ran a complex sql for 30 minutes, without completing, I aborted it , a message window displayed as " Cancel pending, please wait ( This may take some time)". but till now , 1:21 hrs passed, no sign to stop, will you please tell me why this cancelling process takes some much time? what can I do to get rid of this long time cancel processing?
    Many Thanks.

    Without knowing more details (what was the SQL doing, what application are you using, what is the application doing when you hit the cancel button, what is the database doing and waiting on, etc.), it's hard to say. Among the options
    - Your SQL statement made a number of database changes that need to be rolled back and that is a generally slow process
    - Your application isn't actually going to send a request to stop the execution of the SQL statement until the first rows are returned
    - Your application has hung and Oracle isn't doing anything
    Justin

  • Time & cancelled based recovery

    Hi DBAs,
    Any one can give me clear idea about, what is time based recovery and until cancel based recovery.
    Thanks a lot

    Any one can give me clear idea about, what is time based recovery and until cancel based recovery.All are incomplete recovery scenarios.
    refer these links
    *Performing Incomplete Recovery [ID 114199.1]*
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1406803852098
    http://docs.oracle.com/cd/B10500_01/server.920/a96572/performingreco.htm

  • Buenos Aires Summer Time Canceled

    Hi, I'm from Buenos Aires Argentina. Today we supposed to enter in the Summer time but last friday the Government canceled this year summer time so we don't have to change our clocks. My iPhone sync the clock with Apple (my Mac too) and now the clock is one hour ahead and the time zone es GMT -2, this has to be GMT -3.
    Any ideas?

    Make sure Apple knows: http://www.apple.com/feedback/iphone.html
    You'll have to wait for an update for a permanent fix (also on any computer you have).
    In the meantime you could set your time manually and pick a time zone that matches the actual time setting in your location.

  • How to cancel a Timer from inside a TimerTask ?

    I have a web application with this structure:
    Tomcat starts a servlet and that starts a master thread to run once every 10 minutes,
    that master thread in turn starts any number of individual tasks to run until completion,
    the idea being a "shoot and forget" methodology.
    public class MasterTask extends TimerTask {
    // run once every 10 minutes
    // retrieve a list of actions to do, this is from a database, could be 10 could be 100
    // for each action schedule a TimerTask
    // the reason for using a new Timer each time is that any of the action tasks
    // may take a long time or not, i do not want an individual task to wait
    // for a previous one to finish, therefore each task is put on it's own timer
    // also in order to spread resources somewhat there is an incremental delay
    // so the is some time between the start of each task as there can be many
    Timer timeit;
    int delay = 0;
    for ( ActionTask doit : taskList ) {
    timeit = new Timer();
    timeit(doit,delay);
    delay = delay+200;
    public class ActionTask extends TimerTask {
    // perform whatever actions need to be done inside this individual TimerTask
    // at some point the individual task has completed it's work
    // how do i completely remove it from this location ?
    I know that inside the TimerTask i can call cancel() but that will only prevent it from running again it does not actually remove it completely, it remains in existence and therefore uses up memory. What i need to do is call the cancel() method on the Timer in order to remove both the Timer and TimerTask.
    If i do not do this then the program will just keep creating new Timers until eternity.
    ( or basically until i run out of memory )
    How do i call the Timer.cancel() method from INSIDE the TimerTask ?
    ( Note that both classes are seperate classes/files and not inside the same file or class. )
    thanks,
    Erik
    Edited by: Datapunter on Jul 27, 2009 4:06 PM

    Gotcha,
    the Timer does get cancelled but the TimerTask runs to completion first.
    Was expecting a kill() type effect but that is not what cancel() does.
    Servlet started by Tomcat
    package servlet;
    import java.util.*;
    import javax.servlet.ServletException;
    public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
        public void init() throws ServletException {
              Timer timeIt = new Timer();
              timeIt.schedule(new timertasks.testmaster(), 0, 10000); // every 10 seconds
    }master task runs every 10 seconds indefinetly,
    and every 10 seconds it starts (kicks off) 2 new tasks.
    package timertasks;
    import java.util.Timer;
    import java.util.TimerTask;
    public class testmaster extends TimerTask {
         public testmaster() {}
         // scheduled to run once every 10 seconds
         public void run() {
              int delay = 0;
              Timer timeit;
              for ( int count = 0; count < 2 ; count++ ) {
                   timeit = new Timer();
                   timeit.schedule(new ActionTask(timeit), delay, 2000);     // every 2 seconds
                   delay = delay + 200;
    }individual timertask, just comment out the timeit.cancel(); to see the difference in effect.
    package timertasks;
    import java.util.Timer;
    import java.util.TimerTask;
    public class ActionTask extends TimerTask {
         private Timer timeit;
         private int runcounter = 0;
         public ActionTask(Timer timeit) {
              this.timeit = timeit;
         // without cancel then values of runcounter should keep rising and more and more tasks should appear
         // with cancel each should run only once
         public void run() {
              System.out.println("before cancel, runcounter="+runcounter);
              timeit.cancel();
              System.out.println("after cancel, runcounter="+runcounter);
              runcounter++;
    }thanks.

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

    Hi,
    I have following scenario.
    1. My thread to send mail has to run at a fixed time interval thus I am using the following method from the Timer class.
    scheduleAtFixedRate(TimerTask object, start time, interval)
    2. My thread in the class checkDBSendEmail 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 put it some logic to filter data form data base after that it will sends me unique data. Data should be email to different uses based on the list.
    Now the Problem:
    I am receiving duplicate mails on multiple times.
    Is there anything that I am missing in the following that would help me resolve this problem.
    my Servlet inti method is:

    sorry code is here..........
    public class SchduleTimeEmail extends HttpServlet implements SingleThreadModel{
    public void init( ServletConfig servletConfig ) throws ServletException{
    super.init(servletConfig);
    this.config = servletConfig;
    try{
    // specify in the format as in 12.13.52 or 3:30pm
    initialTime = format.parse( config.getInitParameter("initialTime"));
    delay = HOURS_24;
    RunLogger.addLogger("init first try:"); // log file
    catch( ParseException pe ){
    // Log.sendMessage( Log.MESSAGE_LEVEL_INFO , "[TimerServlet]", "startTime could not be parsed from web.xml file" );
    System.out.println("startTime could not be parsed from web.xml file."+pe);
    initialTime = new Date();
    delay = HOURS_24;
    // Timer Must start combination of 15,30,45,00 min for check schdule
    Date dalayTimeMinSec = new Date();
    int currentMin = dalayTimeMinSec.getMinutes();
    int totalDelayTime = 0;
    if(currentMin%15!=0 || currentMin%15 != 15){
    try {
    int delayMin = currentMin % 15;
    totalDelayTime = (15-delayMin) * 1000 * 60;
    dalayTimeMinSec.setSeconds(0);
    Thread.sleep(totalDelayTime);
    RunLogger.addLogger("Thread go for sleep:");
    } catch (InterruptedException ex) {
    RunLogger.addLogger(ex.toString());
    //Start Timer from this time
    timer = new Timer();
    Calendar time = Calendar.getInstance();
    Calendar timeOfDay = Calendar.getInstance();
    try{
    timeOfDay.setTime(initialTime);
    time.set((Calendar.HOUR_OF_DAY), timeOfDay.get(Calendar.HOUR_OF_DAY));
    time.set(Calendar.MINUTE, timeOfDay.get(Calendar.MINUTE));
    time.set(Calendar.SECOND, timeOfDay.get(Calendar.SECOND));
    Calendar startTimeOfTimer = Calendar.getInstance();
    startTimeOfTimer.add( Calendar.MINUTE, 0 );
    // make sure the first timer doesn't fire before the server starts
    if( time.before(startTimeOfTimer) )
    time = startTimeOfTimer;
    System.out.println("TimerServlet: Timer has been set for " + time.getTime() + " '(" + delay + ")'"); // for checking
    checkDBSendEmail msasTask = new checkDBSendEmail();
    timer.scheduleAtFixedRate( msasTask, time.getTime(), delay );
    catch( Exception e ){
    RunLogger.addLogger(e.toString());
    public void destroy(){
    timer.cancel();
    super.destroy();
    and another class is:..
    public class checkDBSendEmail extends TimerTask{
    public void run()
    // System.out.println("Function run : "+ functionExcuteCount++);
    try{
    // DB Logic as well as send e-mail function call
    catch( Exception ex ){
    RunLogger.addLogger(ex.toString());
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    public String getServletInfo() {
    return "Short description";
    // </editor-fold>
    I also checked the email server settings, and I am sure that the email server is not duplicating the emails.
    this code working correctly on my local machine But in live server it duplicating email and still I am receiving duplicate mails.
    Any help is appreciated.
    Thanks,
    Sharda

  • Timer won't stop on Weblogic 10.3.2

    Hi,
    I have a bean with a JEE TimerService. The client calls that bean to create a timer with an initualDuration, say after 5 seconds.
    After the 5 seconds are up, the timeout method is reached.
    Everything works fine.
    The problem is that the timer doesn't stop. The documentation says that a Timer with an initialDuration only (not intervalDuration) should stop after a single timeout has occured.
    But this doesn't happen. The timerout is reached after another 5 seconds, and another, and another etc.
    I even tell the timer to cancel itself inside the timeout method (timer.cancel()), but that won't help either.
    Any suggestions?
    Thanks.

    Hello,
    Umm... i am trying to explain my opinion about your questions ...
    The problem is that the timer doesn't stop. The documentation says that a Timer with an initialDuration only (not intervalDuration)
    should stop after a single timeout has occured.I think that maybe a description dok problem ... a "timer" have to fire from timeservice from a period, but .. is always it the same timer "object"? .. no, it is not ..
    you need a "clock" indeed a "timer" ...
    If you need to set a intervalduration, you have to do a transaction setting the time-out on it ... in a cmp ejb timer, use <trans-timeout-seconds>, and the timer will be killed after this time ...
    But this doesn't happen. The timerout is reached after another 5 seconds, and another, and another etc.This is that do ... another and another, but running differents objects ... watch out the workmanager pool ....
    I even tell the timer to cancel itself inside the timeout method (timer.cancel()), but that won't help either.maybe ... the timer you are using is marked into the timers collection from timerservice ... if you call cancel and the timer is marked running, the cancel call will be rejected ... you need to search into all timers and cancel using your id ...
    Regards

  • Amount of key presses a user makes over time - BPM

    Hi,
    Im working on a small program that needs to get the amount of keypresses a user makes over time.
    Basically its for calcuating the BPM a user is inputting. So a uers taps a beat for 5 seconds and the amount of tap is saved and multiplied by 12 to get the Users BPM.
    So far i have this:
    package Version1;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.*;
    public class muTap extends JFrame implements KeyListener, ActionListener {
        JTextArea display;
         * main - the main method
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    theGUI();
         * muTap constructor
        public muTap(String name) {
            super(name);
         * theGUI - creates the gui for muTap
        public static void theGUI() {
            muTap frame = new muTap("muTap");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Set up the content pane.
            frame.addComponents();
            //Display the window.
            frame.pack();
            frame.setVisible(true);
         * adComponents - adds gui components to muTap
        public void addComponents() {
            JButton button = new JButton("Start");
            button.addActionListener(this);
            display = new JTextArea();
            display.setEditable(false);
            display.addKeyListener(this);
            JScrollPane scrollPane = new JScrollPane(display);
            scrollPane.setPreferredSize(new Dimension(375, 125));
            getContentPane().add(scrollPane, BorderLayout.PAGE_START);
            getContentPane().add(button, BorderLayout.PAGE_END);
        public void keyTyped(KeyEvent e) {
            //Do Nothing
        /** Handle the key pressed event from the text field. */
        public void keyPressed(KeyEvent e) {
            //TODO call the getBPMfromKboard() method
            taps++;
            System.out.println("Tap: " + taps);
        /** Handle the key released event from the text field. */
        public void keyReleased(KeyEvent e) {
            //Do Nothing
        /** Handle the button click. */
        public void actionPerformed(ActionEvent e) {
            //Do Nothing
            //initialCountdown(3, "Start Tapping Fool");
            countDown(3);
         * countDown - a simple countdown timer for use when getting users input.
         * @param time amount of time to count down from
         * @return      true when timer ends.
        public static int taps;
        public void countDown(final int time) {
            taps = 0;
            final Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask()
                int i = time;
                public void run()  {
                    i--;
                    String s = Integer.parseInt(i); // error because of this i.
                    display.setText(s);
                    if (i < 0) {
                        timer.cancel();
                        if(time == 3)
                            display.setText("Start Tapping");
                            countDown(5);
                        else if(time == 5)
                            display.setText("Number of taps: " + taps);
                            //System.out.print("Number of taps" +taps);
            }, 0, 1000);
    }But i get errors when i try running it:
    "Exception in thread "Timer-1" java.lang.RuntimeException: Uncompilable source code"
    It doesnt seem to like me parsing int to string here:
    String s = Integer.parseInt(i); Any ideas? or if youve got suggestions on another way to do it it'd be much appreiated.
    Thanks!

    Korvanica wrote:
    It doesnt seem to like me parsing int to string here:
    String s = Integer.parseInt(i);
    Yikes, you've got that bit of code backward, there partner.
    You use Integer.parseInt to parse a String into an int, not the other way around.
    If you want to change an int to a String, do
    String s = String.valueOf(i)or you can use the various formatters out there.

  • I'm trying to do a spanish lesson but my MacBook Air sound isn't working well. I can't hear anything from the sound system on this computer. Also When I try to Face Time, and someone 's connecting it quits.My battery charger isnt working it on zero all

    Hello If Yal Reading This
    My Macbook Air Ain't Working.
    In Three Ways!!!!!!!!!!!!!!
    1. My Sound
    2. Face Time
    3.Battery
    Sound isnt working loudly when I do spanish lessons
    My Face Time cancels when I connect to another person
    And when I charge my MacBook Air it is always put on zero= 0%

    Reset SMC.     http://support.apple.com/kb/HT3964
    Choose the method for:
    "Resetting SMC on portables with a battery you should not remove on your own".
    If this does not help, contact Apple.
    Best.

  • Stoping timer problem

    Hi!
    I have timer that starts after first user login into the app. Problem is that this timer is alive after i redeploy app. only thing that can kill thet timer is shutdown of timcat. i know that there is timer.cancel() method but can anyone help me and tell me how can i recognize is there some timer active? I have some static variable that is 0 by default, and after timer stars i set that variable to 1, but after redeploying app variable is set to 0 and timer is still active...
    Tnx,
    Stanislav

    i dont know much about timers in java, but it seems a thread problem.
    are you sure that thread starting the timer is a deamon thread?
    http://asahin.net

  • Canceling timers after server restart

    hi,
    i create a couple of timers. while the application server is up i can cancel them by getting the TimerService object of the bean it's associated with, calling getTimers() and cancelling the Timer objects returned from it.
    if i restart the server (let's say it crashed), the timers created in the previous session are back to run - they are persistent by definition. but now i can't cancel them anymore: same getTimers() returns an empty Collection. i think this happens because the old timers from the previous session were not rebound to the new ejbcontext, or something like this.
    my question is: how can i cancel timers, that were re-invoked after server restart.
    thank you.
    Message was edited by:
    cyclid

    Below are my tests that show canceling of timers working as expected:
    Session bean methods:
    public void createTimers()
    {       System.out.println("### CREATE - a single-action timer that expires in 4s");
    ctx.getTimerService().createTimer(4000, "single-action timer that expires in 4s");
    System.out.println("### CREATE - an interval timer that expires in every 2s");
    ctx.getTimerService().createTimer(2000, 2000, "interval timer that expires in every 2s");
    public void cancelAllTimers() {   
         System.out.println("### CANCEL - timers:");     
         for (java.util.Iterator iter = ctx.getTimerService().getTimers().iterator(); iter.hasNext();) {
              Timer timer = (Timer) iter.next();
              System.out.println(" canceling ... " + timer.getInfo());
              timer.cancel();
    public void logCurrentTime() {
         System.out.println("### CURRENT TIME - " + java.util.Calendar.getInstance().getTime());
    public void ejbTimeout(Timer timer)
    {     System.out.println("### EJB TIMEOUT - " + timer.getInfo());       
    Java Client test:
    ejb.cancelAllTimers();
    Thread.sleep(4000);
    ejb.logCurrentTime();
    ejb.createTimers();
    Thread.sleep(8000);
    ejb.cancelAllTimers();
    ejb.logCurrentTime();
    Thread.sleep(8000);
    ejb.logCurrentTime();
    Logs:
    1. Shutdown servers while there is an interval timer
    The log shows the interval timer came back and then was cancel after server restart
    07/02/06 13:46:23 ### CANCEL - timers:
    07/02/06 13:46:27 ### CURRENT TIME - Tue Feb 06 13:46:27 EST 2007
    07/02/06 13:46:27 ### CREATE - a single-action timer that expires in 4s
    07/02/06 13:46:27 ### CREATE - an interval timer that expires in every 2s
    07/02/06 13:46:29 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:46:31 ### EJB TIMEOUT - single-action timer that expires in 4s
    07/02/06 13:46:31 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:46:32 Shutting down OC4J...
    C:\oc4j\10131_061009\j2ee\home>java -jar oc4j.jar
    07/02/06 13:48:12 Oracle Containers for J2EE 10g (10.1.3.1.0) initialized
    07/02/06 13:48:13 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:48:15 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:48:17 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:48:18 ### CANCEL - timers:
    07/02/06 13:48:18 canceling ... interval timer that expires in every 2s
    07/02/06 13:48:22 ### CURRENT TIME - Tue Feb 06 13:48:22 EST 2007
    2. Cancel timers right after they were created
    07/02/06 13:50:11 ### CANCEL - timers:
    07/02/06 13:50:15 ### CURRENT TIME - Tue Feb 06 13:50:15 EST 2007
    07/02/06 13:50:15 ### CREATE - a single-action timer that expires in 4s
    07/02/06 13:50:15 ### CREATE - an interval timer that expires in every 2s
    07/02/06 13:50:17 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:50:19 ### EJB TIMEOUT - single-action timer that expires in 4s
    07/02/06 13:50:19 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:50:21 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:50:23 ### EJB TIMEOUT - interval timer that expires in every 2s
    07/02/06 13:50:23 ### CANCEL - timers:
    07/02/06 13:50:23 canceling ... interval timer that expires in every 2s
    07/02/06 13:50:23 ### CURRENT TIME - Tue Feb 06 13:50:23 EST 2007
    07/02/06 13:50:31 ### CURRENT TIME - Tue Feb 06 13:50:31 EST 2007

  • Timer Class in jsdk 1.4 w2000 doesn't compile

    Since this is based in the tutorial, shouldn't be a big deal but I spent the whole day looking for a solution. Please help!
    The tutorial presents this program:
    //1.3
    import java.util.timer;
    public class Problem {
    public static void main(String[] args) {
    final Timer timer = new Timer();
    timer.schedule(new TimerTask(), 5000);
    System.out.println("In 5 seconds this application will exit. ");
         public class TimerTask implements Timer {
    public void run() {
    System.out.println("Exiting.");
    timer.cancel();
    My problem starts because java.util doesn't have the timer class:
    Problem.java:2: Class java.util.timer not found in import.
    import java.util.timer;
    ^
    Now, JSDK 1.4 doesn't have timer as a package, but as a class, nevertheless, the instruction:
    import java.util.*; // instead of java.util.Timer
    doesn't compile because
    Problem.java:10: Interface Timer of inner class Problem. TimerTask not found.
    Problem.java:6: Class Timer not found in type declaration.
    I think Timer should be expressed as abstract, but how?
    I'm new in Java and feel a little frustrated...

    >
    ProblemSolved.java:3: Class java.util.Timer not found
    in import.
    import java.util.Timer;
    ^
    1 error
    Then you are not using java 1.3. You are using something before that.
    for the Timer and
    javac IteratorDemo.javaIteratorDemo.java:1: Interface java.util.Iterator of
    class IteratorDemo not foun
    d.
    public class IteratorDemo implements
    java.util.Iterator {
    ^
    1 error
    And this suggests that you are using something before 1.2.
    Just a thought...
    Windows comes with the MS version of java, which matches something like 1.1.6. It is in the path. So does you path put the jdk path first or last?

  • Trouble drawing a real time line across X axis.

    Hi,
    I am trying to draw a line across the X axis in real time, but for some reason, the simply cases are way off. For example, If I try to draw the line for two minutes. my line will only make it to about 1 min 45-50 seconds within that time. I tried to make up for the difference by checking the system clock, but that has not helped. Can anyone see something obviously wrong in my code:
    protected class GraphTimerTask extends TimerTask {
         protected static final int DELAY = 31;
         protected long currentTime = 0;
         protected long previousTime = -1;
         private boolean isOn = false;
         protected Timer timer = null;
         public GraphTimerTask(Timer t) {
              this.timer = t;
              isOn = true;
         public void run() {
              if(previousTime > 0) {
                   currentTime += System.currentTimeMillis() - previousTime;
              else {
                   currentTime += DELAY;
                    Graph.this.repaint();
                 previousTime = System.currentTimeMillis();
         protected boolean isOn() { return isOn; }
         protected long getTime() { return currentTime; }
         protected void stop() { isOn = false; timer.cancel(); }
    }currentTime is the actual time that is repainted on my graph when the repaint() is called.

    Timer does not take into account the time taken to process the Timer event. The following is one of my simple examples of how to do something similar to what you want to do and to take into account (parially) the processing time..
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class SimpleAnimation extends JFrame
        public SimpleAnimation()
            super("Simple Annimation Demo");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // The model instance
            AnnimationModel annimationModel = new AnnimationModel();
            // The view of the model
            AnimationView animationView = new AnimationView(annimationModel);       
            animationView.setPreferredSize(new Dimension(640, 480));
            // The view becomes the content pane
            setContentPane(animationView);
            pack();
        private static class AnimationView extends JPanel
            AnimationView(AnnimationModel annimationModel)
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer()
                    public void update(Observable o, Object arg)
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                // Update the view based on the information in the model.
                g.setColor(Color.red);
                // Convert the model positions to view positions
                // in this case by scaling to the actual width and height.
                int xScreenPosition = scaleValue(annimationModel_.getX(), getWidth() - 20 ) + 5;
                int yScreenPosition = scaleValue(annimationModel_.getY(), getHeight() - 20 ) + 5;
                // Display the position of the point
                g.fillOval(xScreenPosition, yScreenPosition, 10, 10);
            private int scaleValue(double v, double size)
                return (int)((v+1.0)*0.5 * size + 0.5);
            // The saved reference to the model
            private AnnimationModel annimationModel_;
        private static class AnnimationModel extends Observable
            AnnimationModel()
                new Thread()
                    public void run()
                        long updatePoint = System.currentTimeMillis();
                        final long delta = 100;
                        final double deltaTheta =  2.0 * Math.PI * delta / (10.0 /* seconds  */ * 1000.0);
                        // Loop forever updating the model
                        // and notifying the observers.
                        while(true)
                            // Wait until the next frame update point
                            // The approach is to calcualte how long we have to wait. In
                            // this way we partially compensate for the processing time
                            updatePoint += delta;
                            synchronized (this)
                                while (updatePoint > System.currentTimeMillis())
                                    try
                                        this.wait(updatePoint - System.currentTimeMillis());
                                    catch (Exception e)
                                        // Nothing to do
                            // Update the model - in this case it is very simple
                            theta_ += deltaTheta;
                            // Notify the observers
                            setChanged();
                            notifyObservers();
                }.start();
            // Model access methods
            public double getX()
                return Math.cos(theta_);
            public double getY()
                return Math.sin(theta_);
            // The angular position of the point
            private double theta_;
        // Simple test main
        static public void main(String[] args)
            new SimpleAnimation().setVisible(true);
    }

  • Timer works if I set the time before the current one

    Hi,
    I've got a block that is part of an actionListener that has 4 buttons, anyway I want the timer to execute something exactly at the time I set it.....but in the code that I have it also executes if i set the time before the current time
    Here's the segmant:
    private class ButtonResponder implements ActionListener
              public void actionPerformed(ActionEvent event) 
                    if (event.getSource() == exitButton)
                                  System.exit(0);
                   if(event.getSource() == setButton)
                        int hour = Integer.parseInt(hours[hourComboBox.getSelectedIndex()]);
                        int min = Integer.parseInt(minutes[minuteComboBox.getSelectedIndex()]);
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(Calendar.HOUR_OF_DAY, hour);
                        calendar.set(Calendar.MINUTE, min);
                        calendar.set(Calendar.SECOND, 0);
                        Date time = calendar.getTime();
                    timer = new java.util.Timer();
                        timer.schedule(new TimerTask()
                             public void run()
                                  JOptionPane.showMessageDialog(null, "it is time");
                        , time, 5*1000);
                   if (event.getSource() == cancelButton)
                        timer.cancel();
              }So if I put zeros in hours and minutes it will execute immediately....how can I make execute at the exact time (so that if the time now is 2:00 and I set it to 1:00 it only executes the next day??
    Message was edited by:
    Octavian

    Bump the day if the time is less than current time.
    Kaj

  • How to cancel Timers permanently?

    We are running our application in Weblogic 10.3. We have an EJB timer that runs all the time and kicks off a piece of code every x minutes. The problem is when an Exception happens and we cancel the timer the timer gets cancelled but some references still remain in the memory which will cause issues when the next time we run the application. (A new timer is then created but the old timer seems to be still there.)
    The way we cancel the timer is as follows:
    Collection timers = ctx.getTimerService().getTimers();
    Collection<Timer> list = timers;
    Iterator<Timer> it = list.iterator();
    while(it.hasNext){
    timer = it.next();
    timer.cancel();
    }

    More information from my findings. If you print the timers to logs, you'll see that the states are different.
    [EJB Timer] id: 146 pk: 1 info: null timer: 1317710283134.17107(60000) state: 2 ejb: PropertyFileRefreshBean(Application: FCM, EJBComponent: FCM_EJB.jar) Thread: Thread[[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads]
    I see state 2 when it is running. And when I perform timer.cancel(), depending on whether it is a transaction or not, it will set the state to 6 or 7. A state 7 will have the timer removed from the sessionContext immediately (I've checked this in the weblogic.jar TimerImpl source). However a state 6 will only mean that the timer has been canceled, but it remains in the session context.
    The problem with my code is that I am checking if getTimer.isEmpty(), which unfortunately, it is not because it is in state 6.
    I'm not sure why doing timer.cancel in 2 different weblogic env (version 9.2 and version 10.3) can result in different states. But I have soon traced the problem to the weblogic-ejb-jar.xml descriptor file. Previously, I was running on a version 8.1 descriptor file. I have then used the DDConvertor tool in in weblogic 10.3 to convert it to the latest. And for some reasons, the timer's behaviour started acting differently.
    What is strange is that, apart from the descriptor header, everything else in the descriptor remains the same. None of the tags, attributes, etc has additional or lesser information. They are totally identical. But the output from the timer was different.
    I hope this helps. Anyone care to shed some light on what I have done wrong?

Maybe you are looking for

  • XP Installation Problem on KM4M-V

    System Specifications: KM4M-V motherboard 1 x PC3200 512 Mb Kingston AMD XP2600+ Sempron Liteon 52x CD-ROM 250 Watt Micro ATX PSU Fan Bus controller 40 Gb Maxtor HD PS2 Mouse PS2 K/b And now the problem . . . Windows XP (Home/Professional) as well as

  • How do I move my old iPhoto library from my external hard drive to my new Mac?

    Hi guys! I recently bought a new MacBook Air as my MacBook Pro was on its last legs... I have my backup for my old MacBook Pro on an external hard drive and I'm trying to put a selection of albums from my old iPhoto onto my new MacBook Air iPhoto. I

  • RFC Error While installing ECC 5.0 on EP 6.0

    Hi All, We have an EP Server installed . Now we are installing ECC 5.0 on it. but at RFC connection stage, we are getting an error message which is below. The Instance number of EP is "00" and that of ECC is "02" now while checking for the RFC it's t

  • How to remove text without destroying the picture?

    I am new in photoshop and I am trying to remove the text down of the picture so that I can add another one. Is watermark, I have seen sosme videos on Youtube but seems didn't work so well to me. If someone can help how to do delete that text and add

  • .flv not working on webpage

    Tried everything I know and some.  Read thru some forums and really no answer.  It must be something simple I am missing. I created These pages all have a flash movie on them (.flv) and all work. http://www.sd22.bc.ca/Career_Programs/gallery.html htt