java定時任務的三種方式

來源:互聯網
上載者:User

標籤:線程池   util   並發   stat   sleep   imp   任務   err   cat   

/** 
 * 普通thread 
 * 這是最常見的,建立一個thread,然後讓它在while迴圈裡一直運行著, 
 * 通過sleep方法來達到定時任務的效果。這樣可以快速簡單的實現,代碼如下
 */  
public class Task1 {  
    public static void main(String[] args) {  
        // run in a second  
        final long timeInterval = 1000;  
        Runnable runnable = new Runnable() {  
            public void run() {  
                while (true) {  
                    // ------- code for task to run  
                    System.out.println("Hello !!");  
                    // ------- ends here  
                    try {  
                        Thread.sleep(timeInterval);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        };  
        Thread thread = new Thread(runnable);  
        thread.start();  
    }  
}  


import java.util.Timer;  
import java.util.TimerTask;  
  
/** 
 *  
 * 於第一種方式相比,優勢 1>當啟動和取消任務時可以控制 2>第一次執行任務時可以指定你想要的delay時間 
 *  
 * 在實現時,Timer類可以調度任務,TimerTask則是通過在run()方法裡實現具體任務。 Timer執行個體可以調度多任務,它是安全執行緒的。 
 * 當Timer的構造器被調用時,它建立了一個線程,這個線程可以用來調度任務。 下面是代碼
 */  
public class Task2 {  
    public static void main(String[] args) {  
        TimerTask task = new TimerTask() {  
            @Override  
            public void run() {  
                // task to run goes here  
                System.out.println("Hello !!!");  
            }  
        };  
        Timer timer = new Timer();  
        long delay = 0;  
        long intevalPeriod = 1 * 1000;  
        // schedules the task to be run in an interval  
        timer.scheduleAtFixedRate(task, delay, intevalPeriod);  
    } // end of main  
}  

import java.util.concurrent.Executors;  
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.TimeUnit;  
  
/** 
 * ScheduledExecutorService是從Java SE5的java.util.concurrent裡做為並發工具類被引進的,這是最理想的定時任務實現方式。  
 * 相比於上兩個方法,它有以下好處: 
 * 1>相比於Timer的單線程,它是通過線程池的方式來執行任務的  
 * 2>可以很靈活的去設定第一次執行任務delay時間 
 * 3>提供了良好的約定,以便設定執行的時間間隔 
 *  
 * 下面是實現代碼,我們通過ScheduledExecutorService#scheduleAtFixedRate展示這個例子,通過代碼裡參數的控制,首次執行加了delay時間。 
 */  
public class Task3 {  
    public static void main(String[] args) {  
        Runnable runnable = new Runnable() {  
            public void run() {  
                // task to run goes here  
                System.out.println("Hello !!");  
            }  
        };  
        ScheduledExecutorService service = Executors  
                .newSingleThreadScheduledExecutor();  
        // 第二個參數為首次執行的延時時間,第三個參數為定時執行的間隔時間  
        service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);  
    }  
}  

java定時任務的三種方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.