freeshare有個功能:應(yīng)用機(jī)器人定時向企業(yè)發(fā)送用戶活躍度的帖子,這里需要通過struts2<listener> 設(shè)定監(jiān)聽,并通過Listener類設(shè)置定時任務(wù),我本來想設(shè)定每周日晚上某個時間執(zhí)行任務(wù),不依賴于我部署的時間,因為一部署就會開始啟動listener:
//Get the Date corresponding to 11:01:00 pm today.
Calendar?calendar?=?Calendar.getInstance(); //這里會獲取當(dāng)前時間周年月日時分秒
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,25);
calendar.set(Calendar.SECOND,0);
Date?time?=?calendar.getTime();
timer?=newTimer();
timer.schedule(newRemindTask(),?time);
timer.schedule(task, time);// time為Date類型:在指定時間執(zhí)行一次(并不會定期執(zhí)行,執(zhí)行完一次就結(jié)束)
這個方法的源碼中有句英文:
Schedules the specified task for execution at the specified time.? If?the time is in the past, the task is scheduled for immediate execution.
我寫的時候是周一,我設(shè)置的calendar是周日,但是他會自動認(rèn)為是上周日(也就是昨天),所以我一運(yùn)行工程他就會執(zhí)行一遍,但是我設(shè)置周二就不會execute immediately。
注意,我的要求是每周定時執(zhí)行,所以其實這樣設(shè)時間是不行的,只能通過:
timer.schedule(task, delay, period)// delay為long,period為long:從現(xiàn)在起過delay毫秒以后,每隔period毫秒執(zhí)行一次。
這種方式定時執(zhí)行,這樣會依賴于我部署的時間,不知道還有沒有其他解決方法。