CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2011
    Posts
    1

    Counter on a Timer

    Hi im trying to get this super simple counter to work on a 1 second delay. But for some reason i can't for the life of me get it to update the counter.

    Code:
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * Schedule a task that executes once every second.
     */
    
    public class Clock {
      Timer timer;
    
      public Clock() {
        timer = new Timer();
        timer.schedule(new RemindTask(), 0, //initial delay
            1 * 1000); //subsequent rate
      }
    
      class RemindTask extends TimerTask {
        int num = 3600; //one hour
    
        public void run() {
          if (num > 0) {     
            int count = 0;
            System.out.println("The number of seconds passed = " + (count = count + 1));
            num--;
          } 
          else {
            System.out.println("Time's up!");
            System.exit(0); //Stops the AWT thread (and everything else)
          }
        }
      }
    
      public static void main(String args[]) {
        System.out.println("About to schedule task.");
        new Clock();
        System.out.println("Task scheduled.");
      }
    }

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Counter on a Timer

    That's because your main method is exiting before the timer has had chance to run. You need to prevent the main thread from immediately terminating - you can do this by calling Thread.sleep(..) or the clock objects wait() method.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    May 2006
    Location
    Norway
    Posts
    1,709

    Re: Counter on a Timer

    Problem here is that your counter is reset to 0 every time your run method runs.

    Just move it out of the run method:
    Code:
    class RemindTask extends TimerTask {
        int num = 3600; //one hour
    
        int count = 0;
        
        public void run() {
          if (num > 0) {     
           
            System.out.println("The number of seconds passed = " + (count = count + 1));
            num--;
          } 
          else {
            System.out.println("Time's up!");
            System.exit(0); //Stops the AWT thread (and everything else)
          }
        }
      }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured