简体   繁体   中英

(Java) How to cancel the timer immediately when some condition is met

The Program
My program asks three math questions such as 10+5? It shows one question at a time on the console. Users answers via the command-line and have 5 seconds to answer . The next question would show only when the user answers the question correctly or when the time is up.

Once the user answers the question correctly within the given time, the next question needs to show (it shouldn't wait until the time is up). The timer should should continue and not restart when the user answers the question wrong. The timer restarts only when the next question shows.

The problems
The program does not immediately cancel the timer after the user answered the question correctly.
Also, the next question would not show up even when the time is up; users have to input something in order to continue to the next question.
Lastly, The next question would also show when users enter an incorrect answer.

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask; 
import java.util.Random;
/** 
 *Simple count down timer demo of java.util.Timer facility.
 */

/*
 * start timer
 * cancel when isLastMoveValid == true
 * start timer again soon
 * */

public class Countdown {
    public static double i = 5;
    public static int answer;
    static Scanner inputs = new Scanner(System.in);
    static Random rand = new Random(); 
    static int num1;
    static int num2;
    static int questionNo = 3;
    public static void main(String args[]) {
        while (questionNo >0) {
            num1 = rand.nextInt(11); 
            num2 = rand.nextInt(11);
            callTimer();       
            System.out.println(num1+ "+" + num2 + "?");
            answer = inputs.nextInt();
        }

    } // end of main method

    public static void callTimer() {

         final Timer timer = new Timer();
         i = 6;

         timer.scheduleAtFixedRate(new TimerTask() {          
             public void run() {
                 i -= 0.001;

                 if (i< 0 || answer == num1 + num2) {
                     questionNo--;              
                     timer.cancel();                
                 }

             } // end of run
         }, 0, 1); // end of scheduleAtFixedRate



    } // end of callTimer
}

You need to have your timer object as a field , so you can access it at any time. See the cancel method how to cancel. If you want to restart the timer, you must create a new object of the timer and the timertask, because they get discarded with the thread.

See documentation on Timer.cancel method:

Terminates this timer, discarding any currently scheduled tasks.Does not interfere with a currently executing task (if it exists).Once a timer has been terminated, its execution thread terminatesgracefully, and no more tasks may be scheduled on it.

For example something like this:

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest
{
    private Timer timer;

    public void cancelTimer()
    {
        this.timer.cancel();
        System.out.println("Canceled timer!");
    }

    public void startTimer()
    {
        // once a timertask is canceled, you can not restart it
        // because the thread is deleted. So we need to create a 
        // new object of a timer and a timertask.
        TimerTask timerTask = new TimerTask()
        {
            @Override
            public void run()
            {
                System.out.println("Hello there!");
            }
        };
        this.timer = new Timer();
        System.out.println("Starting timer ...");
        int period = 1000;
        this.timer.schedule(timerTask, 0, period);
    }

    public static void main(String[] args) throws InterruptedException
    {
        TimerTest tt = new TimerTest();
        tt.startTimer();
        Thread.sleep(5000);
        tt.cancelTimer(); // you can call this method, as soon as u have a correct answer
        Thread.sleep(1000);
        tt.startTimer(); // you can restart your timer as demanded
        Thread.sleep(5000);
        tt.cancelTimer(); // and cancel it again
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM