【问题标题】:Timer and TimerTask not updateTimer 和 TimerTask 不更新
【发布时间】:2014-04-07 11:47:40
【问题描述】:

我有一个可以设置处理时间的应用。问题是当我更新的时候,处理会增加。例如: 最初,计时器从上午 07:00 开始 假设,我将计时器更新为上午 08:00,然后第二天开始,程序将在上午 07:00 和上午 08:00 再次运行。 (07:00AM 还在调度器中,如何删除 07:00AM?) 如何让调度器只在次日上午 08:00 运行?

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");
}

【问题讨论】:

    标签: java timer


    【解决方案1】:

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

    终止此计时器,丢弃任何当前计划的任务。做 不干扰当前正在执行的任务(如果存在)。一旦 计时器已终止,其执行线程正常终止, 并且不能在其上安排更多任务。

    【讨论】:

    • 我是否在 timer.scheduleAtFixedRate(new TimerTask() 之前调用 cancel()?如果我设置了超过 1 个的时间表,那么另一个呢?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2013-03-04
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      相关资源
      最近更新 更多