我有一个可以设置处理时间的应用程序。问题是当我更新时间时,处理会增加。例如:最初计时器在早上7:00开始计时比方说,我将计时器更新为上午8:00,然后第二天开始,程序将在早上7:00再次运行,也将在上午8:00再次运行( 07:00AM还在调度器中,如何删除07:00AM?)如何让调度器只运行第二天早上8点?
public void setKonfigurasi(String name, String value) {
log.info(SERVLET_NAME + "Entering setKonfigurasi");
amBean.setParam(name,value); //update the time into database
//name = 'processFileConf|kodPT|userA|20140312 08:30 AM'
// reschedule timer after configured by user
try {
String kodPT = name.substring(name.indexOf("|") + 1, name.indexOf("|",name.indexOf("|") + 1));
String configStr = value.substring(2); //get the new time
String currentStr = CommonUtil.getCurrentDate();
DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy KK:mm:ss a");
Date currentDate=new Date() ;
Date configDate = dateformat.parse(currentStr+" "+configStr);
long config = configDate.getTime();
long current = currentDate.getTime();
// today
long delay = config-current;
if (delay < 0)
// tomorrow
delay += (1000*60*60*24);
// create the timer and timer task objects
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("showtime for "+kodPT);
processFile("auto"+kodPT);
}
}, delay, 1000*60*60*24);
ServletContextEvent servletContextEvent = EtServletContextListener.getContext();
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.removeAttribute ("timer");
servletContext.setAttribute ("timer", timer);
} catch (Exception e) {
log.error("Exception on date format : "+e.getMessage());
}
log.info(SERVLET_NAME + "Exiting setKonfigurasi");
}
发布于 2014-03-12 09:34:55
您需要在上一个计时器上调用cancel()
并创建一个新的计时器。javadoc说:
终止此计时器,丢弃所有当前计划的任务。不会干扰当前正在执行的任务(如果存在)。一旦定时器终止,它的执行线程就会正常终止,并且不能在它上面调度更多的任务。
发布于 2014-04-07 03:47:40
我已经找到了如何做我想做的事情。我们应该使用javax.ejb.Timer,而不是使用java.util.Timer来创建计时器,因为ejb中的计时器有一个信息来标识每个计时器。Timer Service EJB
https://stackoverflow.com/questions/22346948
复制