如何在基于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
提交
取消
