How to start a new thread when tomcat start

因為資料庫裡有垃圾定期要清理, 所以需要設一個排程定時去檢查, 希望在 tomcat 一執行就可以產生一個thread 默默地工作.

解法:
https://stackoverflow.com/questions/18136098/how-to-start-a-new-thread-when-tomcat-start

滿簡單的, 先增加一個 class:

public class IdiotContextListener implements ServletContextListener {
	public void contextInitialized(ServletContextEvent sce) {
	    //Your logic for starting the thread goes here - Use Executor Service
	}

	public void contextDestroyed(ServletContextEvent sce){
	   //Your logic for shutting down thread goes here
	}
}

java thread 範例:

new Thread(() -> {
System.out.println("hello thread");
}).start();

再看看這個 class 的路徑在那, 加到 web.xml 裡的 <web-app> tag 裡, 範例:

These days I really don’t think you really need to create a new thread like this new Thread() when you have ExecutorService from the java.util.concurrent package is available at your disposal.

For starting a new thread you can define your contextListener in web.xml like this –

<listener>
   <listener-class>com.your-package-path.IdiotContextListener</listener-class>
</listener>

Use a ServletContextListener and start and stop the thread in contextInitialized() and contextDestroyed() methods respectively.

In a Servlet or Filter start and stop the thread in the init() and destroy() methods respectively.

If you don’t know how Thread class works, read the class’ javadoc here. Create your own implementation of a Runnable and pass that to the Thread, then start() it.

On a related note, don’t manage the thread yourself. Use an ExecutorService.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *