How to stop the task scheduled in java.util.Timer class

前端 未结 5 1977
走了就别回头了
走了就别回头了 2020-11-27 12:44

I am using java.util.Timer class and I am using its schedule method to perform some task, but after executing it for 6 times I have to stop its task.

How

相关标签:
5条回答
  • 2020-11-27 13:05

    You should stop the task that you have scheduled on the timer: Your timer:

    Timer t = new Timer();
    TimerTask tt = new TimerTask() {
        @Override
        public void run() {
            //do something
        };
    }
    t.schedule(tt,1000,1000);
    

    In order to stop:

    tt.cancel();
    t.cancel(); //In order to gracefully terminate the timer thread
    

    Notice that just cancelling the timer will not terminate ongoing timertasks.

    0 讨论(0)
  • 2020-11-27 13:10

    Keep a reference to the timer somewhere, and use:

    timer.cancel();
    timer.purge();
    

    to stop whatever it's doing. You could put this code inside the task you're performing with a static int to count the number of times you've gone around, e.g.

    private static int count = 0;
    public static void run() {
         count++;
         if (count >= 6) {
             timer.cancel();
             timer.purge();
             return;
         }
    
         ... perform task here ....
    
    }
    
    0 讨论(0)
  • 2020-11-27 13:12

    Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.

    0 讨论(0)
  • 2020-11-27 13:16

    Terminate the Timer once after awake at a specific time in milliseconds.

    Timer t = new Timer();
    t.schedule(new TimerTask() {
                @Override
                 public void run() {
                 System.out.println(" Run spcific task at given time.");
                 t.cancel();
                 }
     }, 10000);
    
    0 讨论(0)
  • 2020-11-27 13:24
    timer.cancel();  //Terminates this timer,discarding any currently scheduled tasks.
    
    timer.purge();   // Removes all cancelled tasks from this timer's task queue.
    
    0 讨论(0)
提交回复
热议问题