当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Timer cancel()用法及代码示例


Timer类的cancel()方法用于终止此计时器并删除任何当前计划的任务。

用法:

public void cancel()

参数:该函数不接受任何参数。


返回值:该方法没有返回值。

异常:该函数不会引发任何异常。

下面的程序演示了上述函数:

程序1:

// program to demonstrate the 
// function java.util.Timer.cancel() 
  
import java.util.*; 
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // creating timertask, timer 
        Timer timer = new Timer(); 
        TimerTask tt = new TimerTask() { 
  
            public void run() 
            { 
                for (int i = 1; i <= 15; i++) { 
                    System.out.println("working on the task"); 
                    if (i >= 7) { 
                        System.out.println("stop the task"); 
                        // loop stops after 7 iterations 
                        timer.cancel(); 
                        break; 
                    } 
                } 
            }; 
        }; 
        timer.schedule(tt, 1000, 1000); 
    } 
}
输出:
working on the task
working on the task
working on the task
working on the task
working on the task
working on the task
working on the task
stop the task

程序2:

// program to demonstrate the 
// function java.util.Timer.cancel() 
  
import java.util.*; 
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // creating timertask, timer 
        Timer timer = new Timer(); 
        TimerTask tt = new TimerTask() { 
  
            public void run() 
            { 
                for (int i = 1; i <= 15; i++) { 
                    System.out.println("working on the task"); 
                    if (i >= 7) { 
                        System.out.println("stop the task"); 
                        // loop stops after 7 iterations 
                        timer.cancel(); 
                    } 
                } 
            }; 
        }; 
        timer.schedule(tt, 1000, 1000); 
    } 
}
输出:
working on the task
working on the task
working on the task
working on the task
working on the task
working on the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task
working on the task
stop the task


相关用法


注:本文由纯净天空筛选整理自Twinkl Bajaj大神的英文原创作品 Timer cancel() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。