生活随笔
收集整理的這篇文章主要介紹了
java timer 定时任务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 package com.xx.model;
2
3 import java.util.Calendar;
4 import java.util.Date;
5 import java.util.Timer;
6 import javax.servlet.ServletContextEvent;
7 import javax.servlet.ServletContextListener;
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10 import com.xx.model.XXTask;
11
12 public class XXTimerListener
implements ServletContextListener {
13
14 private Timer timer =
null;
15 private static final Log log = LogFactory.getLog(XXTimerListener.
class);
16 final Log logrecords = LogFactory.getLog("records"
);
17
18 public void contextDestroyed(ServletContextEvent arg0) {
19 // TODO Auto-generated method stub
20
21 }
22
23 public void contextInitialized(ServletContextEvent arg0) {
24 // TODO Auto-generated method stub
25
26 try {
27 timer =
new Timer(
true);
28 try {
29 Calendar calendar =
Calendar.getInstance();
30 calendar.set(Calendar.HOUR_OF_DAY, 10);
// 上午10點
31 calendar.set(Calendar.MINUTE, 0
);
32 calendar.set(Calendar.SECOND, 0
);
33 Date date = calendar.getTime();
// 第一次執行定時任務的時間
34 // 如果第一次執行定時任務的時間 小于當前的時間
35 // 此時要在 第一次執行定時任務的時間加一天,以便此任務在下個時間點執行。如果不加一天,任務會立即執行。
36 if (date.before(
new Date())) {
37 date = addDay(date, 1
);
38 }
39 timer.schedule(
new XXTask(),date,24*3600*1000
);
40 log.info("任務創建成功!"
);
41 }
catch (Exception e) {
42 log.error("任務創建失敗!"
, e);
43 }
44 }
catch (Exception e) {
45 // TODO Auto-generated catch block
46 e.printStackTrace();
47 }
48 }
49
50 public Date addDay(Date date,
int num) {
51 Calendar startDT =
Calendar.getInstance();
52 startDT.setTime(date);
53 startDT.add(Calendar.DAY_OF_MONTH, num);
54 return startDT.getTime();
55 }
56 }
1 package com.xx.model;
2 import java.util.TimerTask;
3 import org.apache.commons.logging.Log;
4 import org.apache.commons.logging.LogFactory;
5 /**
6 * @author qjl
7 *
8 */
9 public class XXTask
extends TimerTask {
10
11 private static final Log log = LogFactory.getLog(XXTask.
class);
12 MeasureCountsAjax mscAjax =
new MeasureCountsAjax();
13
14 @Override
15 public void run() {
16
17 log.debug("定時任務" +
new Date(System.currentTimeMillis()));
18 try {
19 //定時任務要執行的方法寫這里
20 }
catch (Exception e) {
21 log.error("定時運行失敗"
, e);
22 }
finally {
23 }
24 }
25 }
?
1 <listener>
2 <listener-
class>
3 com.xx.model.XXTimerListener
4 </listener-
class>
5 </listener>
?
轉載于:https://www.cnblogs.com/qinjunli/p/4618671.html
總結
以上是生活随笔為你收集整理的java timer 定时任务的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。