java定時執行簡介

import java.util.TimerTask;

public class MyTimerTask extends TimerTask  {
public void run(){
System.out.println("程序運行");
}
}

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

public class Test {
public static void main(String[] args){
Timer timer = new Timer();
//timer.schedule(new MyTimerTask(), 5000);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設置日期格式
System.out.println(df.format(new Date()));// new Date()爲獲取當前系統時間
timer.schedule(new MyTimerTask(),0,2000);//第二個參數表示當前時間開始,第三個參數表示每隔2s執行一次
}

}


在web工程中可以配置一個servlet,在程序啓動時開始計時,即可實現定時器效果,如下所示:

     <servlet>
<servlet-name>Timing</servlet-name>
<servlet-class>com.Servlet</servlet-class>
<load-on-startup>6</load-on-startup>
</servlet>


public  RankServlet extends HttpServlet {
private Timer timer = null;
private static final long serialVersionUID = 1L;
private RankingService service;

/**
* Constructor of the object.
*/
public RankServlet() {
super.destroy();
}


/**
* Initialization of the servlet. <br>

* @throws ServletException
*             if an error occurs
*/
public void init() throws ServletException {
ServletContext context = this.getServletContext();
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(context);
service = (RankingService) wac.getBean("rankingService");
timer = new Timer(true);
Calendar cal = Calendar.getInstance();
 // 每天定點執行
cal.set(Calendar.HOUR_OF_DAY,24);//每天晚上12點
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
   timer.schedule(new RankTimerTask(service),cal.getTime(),24*60*60*1000);
}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章