Recurring Countdown Timer in Java

前端 未结 4 1029
自闭症患者
自闭症患者 2021-01-21 21:49

I\'m trying to implement a countdown timer into a pre-existing public class and I have a few questions.

An overview: I want to have a timer within a program that counts

相关标签:
4条回答
  • 2021-01-21 22:03

    If I were you, I'd use:

    1. an AtomicInteger variable which would keep the current countdown value;
    2. a timer thread that would wake up every 1s and decrementAndGet() the variable, comparing the result to zero and terminating the app if the result is zero;
    3. (possibly) a thread that would also wake up every 1s to repaint the GUI -- the best approach here depends on your GUI framework.

    Finally, whenever you need to reset the count back to 60s, you just call set(newValue) from any thread.

    The timer thread's run() method could be as simple as:

    for (;;) {
      if (counter.decrementAndGet() <= 0) {
        // TODO: exit the app
      }
      Thread.sleep(1000);
    }
    

    I think it's much easier to get this right than trying to manage multiple Timer objects.

    0 讨论(0)
  • 2021-01-21 22:19

    You could use java.util.Timer to schedule an execution of a method and then cancel it if the requirements is met.

    Like this:

    timer = new Timer();
    timer.schedule(new Task(), 60 * 1000);
    

    And then make a class like this to handle the timerschedule:

    class Task extends TimerTask {
        public void run() {
          System.exit(0);
        }
      }
    

    If the requirements is met, then do this to stop it from executing:

    timer.cancel();
    
    0 讨论(0)
  • 2021-01-21 22:22

    The best way to impliment timer in your application is using some sheduler frameworks like Quartz

    0 讨论(0)
  • 2021-01-21 22:26

    If you need to update your GUI better to use SwingWorker http://en.wikipedia.org/wiki/SwingWorker I would write something like this:

    SwingWorker<String, Integer> timer = new SwingWorker<String, Integer>() {
        Integer timer=60;
        @Override
        protected String doInBackground() throws Exception {
          //update guiModel
          //label.setText(timer.toString());
            while(timer>0){
            Thread.sleep(1000);
            timer--;
            }
            return null;
        }
        @Override
         public void done(){
             System.exit(0);
         } 
    };
    
    JButton restart = new JButton(){
        {
      addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    timer.cancel(true);
                    timer.execute();
                }
            });      
        }
    };
    
    0 讨论(0)
提交回复
热议问题