TimerTask cancel() in Java

cancel(): This method is available in java.util.TimerTask class of Java.

Syntax:

boolean java.util.TimerTask.cancel()

This method cancels this timer task.

Parameters: NA

Returns: true if this task is scheduled for one-time execution and has not yet run, or this task is scheduled for repeated execution returns false if the task was scheduled for one-time execution and has already run, or if the task was never scheduled, or if the task was already canceled.

Exceptions: NA

Approach

Java

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

public class TimerTaskcancel {
    public static void main(String[] args) {

        TimerTask task = new TimerTask() {

            @Override
            public void run() {

            }
        };
        Timer timer = new Timer();

        timer.scheduleAtFixedRate(task, new Date(), 1000);

        System.out.println(task.cancel());
    }

}

Output:

true


No comments:

Post a Comment