How to get time left in a java.util.Timer?

2019-03-04 12:28发布

How can I get the time left in a util.Timer? What I want to do is to add a progressbar that displays time left until the timer starts over.

This is what I've got this far:

int seconds = 8;

java.util.Timer timer = new Timer();
timer.schedule( new TimerTask(){
    public void run(){
        // Do something
        // Add a progressbar that displays time left until the timer "starts over".
    },0,(long) (seconds*1000));

2条回答
Ridiculous、
2楼-- · 2019-03-04 12:46

You would need a second timer to refresh the gui in a specific interval.
Another way to achieve this, would be to activate a single timer every second and update the counting in the ui. If the time is up, call your specific action.

A simple expample with console output only:

TimerTask task = new TimerTask()
{
    int seconds = 8;
    int i = 0;
    @Override
    public void run()
    {
       i++;

       if(i % seconds == 0)
           System.out.println("Timer action!");
       else
           System.out.println("Time left:" + (seconds - (i %seconds)) );
    }
};

Timer timer = new Timer();
timer.schedule(task, 0, 1000);

It's output would be:

Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
Time left:5
Time left:4
Time left:3
Time left:2
Time left:1
Timer action!
Time left:7
Time left:6
...

Then simply change the System.out's with your code to update the progress bar. Remember: java.util.Timer starts its own Thread. Swing is not thread safe, so you need to put every gui changing code into SwingUtilities.invokeLater()!
If you're not doing any long running tasks, every time your timer reachs the 8 seconds mark, you may want to use javax.swing.Timer directly. It uses the EDT and not its own Thread, so you don't need to synchronize your calls to Swing components with SwingUtilities.invokeLater().

Also see:
javax.swing.Timer vs java.util.Timer inside of a Swing application

查看更多
闹够了就滚
3楼-- · 2019-03-04 12:55

All you need to do is declare a long variable timeleft in your MainActivity.

long timeleft; 

Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )

        timer = new CountDownTimer(time, 1000) {
           @Override
            public void onTick(long millisecondsUntilFinished) {
                timeleft = millisecondsUntilFinished;
            }
          }

Your app can access then the variable timeleft every time you need to check how much time is left.

查看更多
登录 后发表回答