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

前端 未结 5 2011
走了就别回头了
走了就别回头了 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.

提交回复
热议问题