如何在基于servlet的Web應用程序中運行后臺任務?我正在使用Java,我希望在我的應用程序中繼續運行一個servlet,但是我不知道如何實現它。我的servlet有一種方法,它每天提供數據庫中用戶的計數,以及整個數據庫中的用戶總數。因此,我想讓servlet繼續運行。
3 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
startTask()
main
.
public void startTask(){ // Create a Runnable Runnable task = new Runnable() { public void run() { while (true) { runTask(); } } }; // Run the task in a background thread Thread backgroundThread = new Thread(task); // Terminate the running thread if the application exits backgroundThread.setDaemon(true); // Start the thread backgroundThread.start();}public void runTask(){ try { // do something... Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }}
添加回答
舉報
0/150
提交
取消