使用Java中的Timer和TimerTask

來源:互聯網
上載者:User

      有的時候我們需要每隔一段時間去執行某個任務,在Java中提供了Timer and TimerTask來完成這個任務,本文提供一個應用程式的原始碼告訴你如何使用這兩個類。

      Timer和TimerTask的方法很少,使用起來也非常方便。希望如果遇到問題參考一下API doc,裡面寫的很清楚。TimerTask是個抽象類別,他擴充了Object並實現了Runnable介面,因此你必須在自己的Task中實現public void run()方法。這也就是我們需要執行的具體任務。Timer實際上是用來控制Task的,他提供的主要方法是重載的schedule()方法。我們這裡將使用schedule(TimerTask task,long time,long internal)方法來說明如何使用它。

      下面直接提供應用程式的原始碼,有得時候感覺說的太多,對初學者作用並不是很大。但是當把代碼給他們看了以後,很容易就接受了。下面我要完成的任務就是每隔3秒鐘從一個檔案中把內容讀出來並列印到控制台,檔案的內容如下:
ming.txt
hello world
beijing
basketball
java
c/c++
這裡涉及到一些IO的知識,但並不複雜。我們使用BufferedReader從檔案裡面讀取內容,一行一行的讀取,代碼如下:

   try
   {
    BufferedReader br = new BufferedReader(new FileReader("ming.txt")); 
    String data = null;
    while((data=br.readLine())!=null)
    {
     System.out.println(data); 
    } 
   } 
   catch(FileNotFoundException e)
   {
    System.out.println("can not find the file"); 
   }
   catch(IOException e)
   {
    e.printStackTrace(); 
   }
在主程式中我們啟動timer讓他開始執行讀取檔案的工作。整個程式的內容如下
import java.util.*;
import java.io.*;

public class TimerUse
{
 public static void main(String[] args)
 {
  PickTask pt = new PickTask();
  pt.start(1,3); 
 } 
}

class PickTask
{
 private Timer timer;

 public PickTask()
 {
  timer = new Timer();
 }
 
 private TimerTask task = new TimerTask()
 {
  public void run()
  {
   
   try
   {
    BufferedReader br = new BufferedReader(new FileReader("ming.txt")); 
    String data = null;
    while((data=br.readLine())!=null)
    {
     System.out.println(data); 
    } 
   } 
   catch(FileNotFoundException e)
   {
    System.out.println("can not find the file"); 
   }
   catch(IOException e)
   {
    e.printStackTrace(); 
   }
   
  } 
 };
 
 public void start(int delay,int internal )
 {
  timer.schedule(task,delay*1000,internal*1000); 
 }
 
}

程式的輸出結果為:

Microsoft Windows XP [版本 5.1.2600]
(C) 著作權 1985-2001 Microsoft Corp.

C:/>java TimerUse
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++
hello world
beijing
basketball
java
c/c++

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.