简体   繁体   中英

How to stop a TimerTask in Java

I have implemented a TimerTask in Java and i need to stop the Thread after a period of time:

        .... 
        timer = new Timer(); // At this line a new Thread will be created

        TimerTask timerTask = new TimerTask() {

            int tweetCounter = 0;
            String message;

            @Override
            public void run() {
                try {
                    while ((message = reader.readLine()) != null && (tweetCounter < 100)) {
                        bucket.add(message);
                        tweetCounter++;

                        out.println("Number of messages: " + tweetCounter);
                        out.println("Nano Time: " + System.nanoTime());

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        timer.schedule(timerTask, 30000);
        ......

At this point i try :

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

After that nothing happens and the program never exits. How can i stop the TimerTask thread?

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

will work .

int java.util.Timer.purge()

Removes all canceled tasks from the task queue. If there are no other references on the tasks, then after this call they are free to be garbage collected.

Returns: the number of canceled tasks that were removed from the task queue.

 Timer timer = new Timer();
    TimerTask tt = new TimerTask(){
        public void run(){
            Calendar cal = Calendar.getInstance(); //this is the method you should use, not the Date(), because it is desperated.

            int hour = cal.get(Calendar.HOUR_OF_DAY);//get the hour number of the day, from 0 to 23

            if(hour ==9){
                try{
                    listAllUsers();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                System.out.println("doing the scheduled task");
            }
            else{

                System.out.println(" Todays task already done");
            }
        }
    };
    timer.schedule(tt, 0, 10000);// delay the task 10 seconds, and then run task after evey one minute

try this working for me

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