簡體   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