[英]Timer and TimerTask not update
I have an app that could set the time for processing. 我有一个可以设置处理时间的应用程序。 The problems is when I update the time, the processing will increase.
问题是当我更新时间时,处理会增加。 For example: Initially the timer start at 07:00AM Let say, I update the timer to 08:00AM then the next day onwards, the program will run again at 07:00AM and also at 08:00AM.
例如:最初,计时器从07:00 AM开始运行。可以说,我将计时器更新为08:00 AM,然后第二天开始,该程序将在07:00 AM和08:00 AM再次运行。 (The 07:00AM is still in scheduler, how to remove the 07:00AM?) How to make the scheduler to only run the 08:00AM the next day?
(07:00 AM仍在调度程序中,如何删除07:00 AM?)如何使调度程序在第二天只运行08:00 AM?
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");
}
You need to call cancel()
on the previous timer and create a new one. 您需要在前一个计时器上调用
cancel()
并创建一个新计时器。 The javadoc says: Javadoc说:
Terminates this timer, discarding any currently scheduled tasks.
终止此计时器,放弃任何当前计划的任务。 Does not interfere with a currently executing task (if it exists).
不干扰当前正在执行的任务(如果存在)。 Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.
计时器终止后,其执行线程将正常终止,并且无法在其上安排更多任务。
I have found out about how to do what I want. 我发现了如何做自己想做的事。 Instead of using java.util.Timer to create the timer, we should use javax.ejb.Timer since the Timer in ejb have an info to identified each timer.
不应使用java.util.Timer创建计时器,而应使用javax.ejb.Timer,因为ejb中的Timer具有标识每个计时器的信息。 Timer Service EJB
计时器服务EJB
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.