java.util.TimerTask.cancel() Method


Advertisements


Description

The cancel() method is used to cancel this timer task.

Declaration

Following is the declaration for java.util.TimerTask.cancel() method.

public boolean cancel()

Parameters

NA

Return Value

The method call returns true if this task is scheduled for one-time execution and has not yet run.It returns false if the task was scheduled for one-time execution and has already run.

Exception

NA

Example

The following example shows the usage of java.util.TimerTask.cancel()

package com.tutorialspoint;

import java.util.*;

public class TimerTaskDemo {
   public static void main(String[] args) {
      
      // creating timer task, timer
      TimerTask task = new TimerTaskCancel();
      Timer timer = new Timer();

      // scheduling the task
      timer.scheduleAtFixedRate(task, new Date(), 1000);

      // cancelling the task
      System.out.println("cancelling task: "+task.cancel());
   }
   // this is the implementation method
   
   public void run() {
      System.out.println("Working");
   }
}

Let us compile and run the above program, this will produce the following result.

cancelling task: true
Working

java_util_timertask.htm


Advertisements
E-Books Store