當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。