日期:2014-05-16  浏览次数:20461 次

通过线程去实现项目启动后每隔段时间去扫描数据库

? <servlet-name>DataSyn</servlet-name>
? <servlet-class>com.datasyn.DataSyn</servlet-class>
? <init-param>
?? <param-name>interval</param-name>
?? <param-value>5000</param-value>
? </init-param>
? <load-on-startup>1</load-on-startup>??????????//项目启动就执行这个servlet
?</servlet>
?<servlet-mapping>
? <servlet-name>DataSyn</servlet-name>
? <url-pattern>/servlet/DataSyn</url-pattern>
?</servlet-mapping>

?

?

servlet类中的的init和destroy方法:

?

public class DataSyn extends HttpServlet {

?private static Logger? log = Logger.getLogger(DataSyn.class.getName());
?private Thread t = null;
?private boolean istop = false;


?/**
? * Constructor of the object.
? */
?public DataSyn() {
??super();
?}

?

?

?/**
? * Initialization of the servlet. <br>
? *
? * @throws ServletException if an error occurs
? */
?public void init() throws ServletException {
??System.out.println("DataSyn init 准备启动");??

??Runnable r = new Runnable() {?????????? //匿名内部类
???Resouce resource = new Resouce();
???OpDb oD = new OpDb();
???public void run() {??????????????????????????//实现runnable接口的run方法
????????while(!istop)
????{
?????try {
??????Thread.sleep(Integer.parseInt(DataSyn.this.getInitParameter("interval")));??//此线程每隔段时间休眠
?????} catch (NumberFormatException e) {
??????e.printStackTrace();
?????} catch (InterruptedException e) {
????????e.printStackTrace();
?????}????
?????resource.work();???????? //具体的数据库操作写在这方法里
?????}
???}
??};
??t = new Thread(r);
??t.start();??????????????????? //开始执行此线程的方法run
?}

?

?/**
? * Destruction of the servlet. <br>
? */
?public void destroy() {
??super.destroy(); // Just puts "destroy" string in log
??// Put your code here
??istop = true;
??try {
???t.join();
??} catch (InterruptedException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
??System.out.println("destroy");
?}


}

?

?