2010-06-08 79 views

回答

1

實施ServletContextListener;在contextInitialized方法:

ServletContext servletContext = servletContextEvent.getServletContext(); 
try{ 
// create the timer and timer task objects 
    Timer timer = new Timer(); 
    MyTimerTask task = new MyTimerTask(); //this class implements Callable. 

// get a calendar to initialize the start time 
    Calendar calendar = Calendar.getInstance(); 
Date startTime = calendar.getTime(); 

    // schedule the task to run hourly 
timer.scheduleAtFixedRate(task, startTime, 1000 * 60 * 60); 

    // save our timer for later use 
    servletContext.setAttribute ("timer", timer); 
} catch (Exception e) { 
servletContext.log ("Problem initializing the task that was to run hourly: " + e.getMessage()); 
} 

編輯您的web.xml中有提及你的監聽器實現:

<listener> 
    <listener-class>your.package.declaration.MyServletContextListener</listener-class> 
</listener> 
+0

感謝@ring,@Balus,@Peter,你所有的答案都是有用的,我跑一個例子成功,但我必須選擇一個答案:(我選擇了@ring答案,因爲他添加了最後一行,Listener-class。謝謝你們。 – Abdullah 2010-06-08 23:35:04

4

您正在Glassfish Java EE服務器上運行,因此您應該有權訪問EJB Timer服務。

下面是一個例子:

http://java-x.blogspot.com/2007/01/ejb-3-timer-service.html

我曾經在JBoss API的早期版本,並且工作得很好。

目前我們傾向於下降石英在戰爭中使用的定時執行,所以它也適用於我們的碼頭髮展情況

3

您需要檢查,如果服務器實現使用的載體射擊這樣的任務。如果它不支持它,或者你想獨立於服務器,那麼實現一個ServletContextListener鉤住webapp的啓動並使用ScheduledExecutorService在給定的時間和間隔執行任務。

這裏有一個基本的開球例如:

public class Config implements ServletContextListener { 

    private ScheduledExecutorService scheduler; 

    public void contextInitialized(ServletContextEvent event) { 
     scheduler = Executors.newSingleThreadScheduledExecutor(); 
     scheduler.scheduleAtFixedRate(new Task(), millisToNext1000, 1, TimeUnit.DAYS); 
    } 

    public void contextDestroyed(ServletContextEvent event) { 
     scheduler.shutdown(); 
    } 

} 

Task實現CallablemillisToNext1000是米利斯到下一個10:00的量。您可以使用CalendarJodaTime來計算它。作爲非Java標準的替代品,您也可以考慮使用Quartz

相關問題