怎样才能让一段代码每隔一段时间执行一次?

实现的方法有两种不过都是继承于线程类来实现的。

1。

 public void run() {
    while (true) {
      try {
        sleep(10000L);  //间隔10s执行一次!
      }
      catch (Exception ex) {
        ToolBox.getLogger().error("Executing the sleep operation error!");
        ex.printStackTrace();
      }
      OperationExecute();//你的操作
    }
  }

 

    

2。采用Timer 类和TimerTask 类配合实现
在Timer 里面有一个时间间隔执行任务的方法schedule的方法可以达到你的要求!

Timer tim = new Timer();
TimerTask tTask = new TimerTask(); //在里面实现你的操作
tim.schedule(tTask,0,10000);//间隔时间10000你自己设定

 

posted @ 2013-08-15 08:47  三星蓝  阅读(1061)  评论(0编辑  收藏  举报