繁体   English   中英

Timer和TimerTask无法更新

[英]Timer and TimerTask not update

我有一个可以设置处理时间的应用程序。 问题是当我更新时间时,处理会增加。 例如:最初,计时器从07:00 AM开始运行。可以说,我将计时器更新为08:00 AM,然后第二天开始,该程序将在07:00 AM和08:00 AM再次运行。 (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");
}

您需要在前一个计时器上调用cancel()并创建一个新计时器。 Javadoc说:

终止此计时器,放弃任何当前计划的任务。 不干扰当前正在执行的任务(如果存在)。 计时器终止后,其执行线程将正常终止,并且无法在其上安排更多任务。

我发现了如何做自己想做的事。 不应使用java.util.Timer创建计时器,而应使用javax.ejb.Timer,因为ejb中的Timer具有标识每个计时器的信息。 计时器服务EJB

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM