簡體   English   中英

在java中創建后台線程的最佳方法

[英]Best way to create a background thread in java

創建后台線程的最佳方法是什么,每15分鍾運行一次以從數據庫中獲取數據?

下面是我所擁有的代碼,我認為它在生產中會正常工作,但是我還有其他更好的方法或我應該注意的事情嗎?

private static void checkDatabaseEveryXMinutes() {
    new Thread() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(checkingAfterEveryXMinutes);
                    getDataFromDatabase();
                } catch (InterruptedException ex) {
                    //log here
                } catch (Exception e) {
                    //log here
                }
            }
        }
    }.start();
}

使用上面的代碼有什么不利之處。 ScheduledExecutorService與TimerTask的比較如何?

哪種方式更好?

如果有更好的方法,我會對此代碼的任何示例基礎表示贊賞。

ScheduledExecutorService將返回一個Future,它有一個額外的方法來檢查Runnable是否完成。 兩者都有取消Runnable的方法。 對於像這樣的重復任務,檢查它是否已完成,可能不會有多大用處。 但是,它是用jdk 1.5並發api引入的,它絕對應該用來代替舊的並發/線程api(Timer和TimerTask是jdk 1.3)。 它們將更強大,性能更好。 他們有一個非常類似的例子如您的使用情況下,在Java文檔在這里

這是一個樣本:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskExample {
    private final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

    public void startScheduleTask() {
    /**
    * not using the taskHandle returned here, but it can be used to cancel
    * the task, or check if it's done (for recurring tasks, that's not
    * going to be very useful)
    */
    final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
        new Runnable() {
            public void run() {
                try {
                    getDataFromDatabase();
                }catch(Exception ex) {
                    ex.printStackTrace(); //or loggger would be better
                }
            }
        }, 0, 15, TimeUnit.MINUTES);
    }

    private void getDataFromDatabase() {
        System.out.println("getting data...");
    }

    public void shutdowh() {
        System.out.println("shutdown...");
        if(scheduler != null) {
            scheduler.shutdown();
        }
    }

    public static void main(String[] args) {
        final ScheduledTaskExample ste = new ScheduledTaskExample();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                ste.shutdowh();
            }
        });
        ste.startScheduleTask();

    }
}

您可以嘗試使用java.util.TimerTaskjava.util.Timer

例子是在這里 : -

Timer t = new Timer();

t.scheduleAtFixedRate(
    new TimerTask()
    {
        public void run()
        {
            System.out.println("3 seconds passed");
        }
    },
    0,      // run first occurrence immediately
    3000);

tieTYT是對的。 如果在應用程序服務器中使用它,則可以使用特定服務器的ejbtimer服務

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM