简体   繁体   中英

How to stop the timer in java

I have a timer method that runs everytime a user inputs something. Basically the user has a minute to input something or the timer will print a response, but it won't print a response if the user inputs something before the timer runs out of time. Basically, I am having trouble cancelling the last timer and calling a new one, because if I don't cancel the timer, the previous timer keeps running while new one keep getting called so it just makes a huge mess. My methods are below

Main:

public static void main(String[] args) {
     while(true) {
          runner();
     }
}

Runner:

public static void runner() {
     timer();
     String s = input.nextLine();
     System.out.println(s);

}

Timer:

public static void timer() {
     TimerTask task = new TimerTask() {
           public void run() {
                System.out.println("Say something already!");
           }
    };
    long delay = TimeUnit.MINUTES.toMillis(1);
    Timer t = new Timer();
    t.schedule(task, delay);
}

How exactly will I make this cancel. Someone has to me to use the cancel() method in the TimerTask class but I don't understand where to call or even how.

Have timer() method return the TimerTask object, and when input.nextLine() returns, call TimerTask.cancel().

public static void runner() {
     TimerTask t = timer();
     String s = input.nextLine();
     t.cancel();
     System.out.println(s);
}

public static void timer() {
     TimerTask task = new TimerTask() {
           public void run() {
                System.out.println("Say something already!");
           }
    };
    long delay = TimeUnit.MINUTES.toMillis(1);
    Timer t = new Timer();
    t.schedule(task, delay);
    return task;
}

Could also return the Timer instead and call Timer.cancel()

I guess this could work:

Main:

TimerTask task;

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    runner();

    while(true) {

        timer(); //run timer
        String line = scan.nextLine(); //read line (happens after hit Enter)
        System.out.println(line);
        //if line is read, then rerun timer which has on next iteration
    }

}

Timer:

public static void timer() {

    if(null != task) {
        task.cancel();
    }

    task = new TimerTask() {
           public void run() {
                System.out.println("Say something already!");
                //timer(); reinit maybe after 1 min again?
           }
    };

    long delay = TimeUnit.MINUTES.toMillis(1);
    Timer t = new Timer();
    t.schedule(task, delay);
}

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