Tomcat定时任务
原文:
The ? load-on-startup ? element ? indicates ? that ? this ? servlet ? should ? be ? loaded ? (instantiated ? and ? have ? its ? init() ? called) ? on ? the ? startup ? of ? the ? web ? application. ? The ? optional ? contents ? of ? these ? element ? must ? be ? an ? integer ? indicating ? the ? order ? in ? which ? the ? servlet ? should ? be ? loaded. ? If ? the ? value ? is ? a ? negative ? integer, ? or ? the ? element ? is ? not ? present, ? the ? Container ? is ? free ? to ? load ? the ? servlet ? whenever ? it ? chooses. ? ? If ? the ? value ? is ? a ? positive ? integer ? or ? 0, ? the ? container ? must ? load ? and ? initialize ? the ? servlet ? as ? the ? application ? is ? deployed. ? The ? container ? must ? guarantee ? that ? servlets ? marked ? with ? lower ? integers ? are ? loaded ? before ? servlets ? marked ? with ? higher ? integers. ? The ? container ? may ? choose ? the ? order ? of ? loading ? of ? servlets ? with ? the ? same ? load-on-start-up ? value.
?
譯文:
load-on-startup 這個元素的含義是在服務器啟動的時候就加載這個servlet(實例化并調用init()方法).這個元素中的可選內容必須為一個整數,表明了這個servlet被加載的先后順序.當是一個負數時或者沒有指定時,則表示服務器在該servlet被調用時才加載。當值為0或者大于0時,表示服務器在啟動時就加載這個servlet.該容器肯定可以保證被標記為更小的整數的servlet比被標記為更大的整數的servlet更先被調用,還可已選擇同樣的load-on-start-up值來夾在servlets.
補充:正數的值越小,啟動該servlet的優先級越高。
修改web.xml
增加<load-on-startup>配置,可以使<servlet-class>中的類隨Tomcat啟動而自動啟動。
<servlet><servlet-name>ServerRun</servlet-name><servlet-class>com.xxx.ServerRun</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>ServerRun</servlet-name><url-pattern>/ServerRun</url-pattern></servlet-mapping>
新建一個serlet ServerRun
public class ServerRun extends HttpServlet {private Timer timer = null;public void init(ServletConfig config) throws ServletException {super.init(config);timer = new Timer(true);timer.schedule(new MyTask(), 1000, 1000); }public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}public void destroy() {}
}
import java.util.TimerTask;public class MyTask extends TimerTask {@Overridepublic void run() {System.out.println("【測試定時器】>>>");}
}
參考:http://blog.csdn.net/sjerry_9/article/details/8364751
http://blog.csdn.net/great1681/article/details/4048416
總結
以上是生活随笔為你收集整理的Tomcat定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: String和常量池
- 下一篇: 编程经验