Bobby Pratama
Bobby Pratama

Reputation: 96

Java set timer to pause and reset timer

How can i Pause timer in Java, for example i have timer that has 20 seconds and when timer is 0, the timer will pause 10 seconds and then the timer will reset (back to 20 sec).

for (int c =20; c>=0; c--){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Upvotes: 1

Views: 815

Answers (2)

ravthiru
ravthiru

Reputation: 9633

You can use Timer task and pause the timer for 10 seconds after execution as follows

public static void main(String[] args) {
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            System.out.println("TimerTask ");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    Timer timer = new Timer();
    timer.schedule(task,0,20000);
}

Upvotes: 0

Joyson
Joyson

Reputation: 3040

You can add a loop outside the for loop. After the for loop finishes execution the statement immediately after that will be executed which is the Thread.sleep(10000) statement. After that it will go the the next iteration of while loop which will reset c to 20 again and thread will sleep for 20 seconds.

while(true)
{
for (int c =20; c>=0; c--){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
  Thread.sleep(10000);
}

What is your exact requirement for putting the thread to sleep for 10 seconds?

Upvotes: 1

Related Questions