![[8.5.5.4 或更新版本]](../ng_v8554.gif)
配置受管理排程執行程式
您可以配置 ManagedScheduledExecutorService 實例,來排程非同步作業,以便與要從中排程作業之執行緒的執行緒環境定義搭配執行。Java™ EE 應用程式的最佳作法是避免直接管理它們自己的執行緒;因此,ManagedScheduledExecutorService 會延伸 JSE ExecutorService,藉以在應用程式伺服器環境內排程非同步作業。您也可以配置 ManagedScheduledExecutorService,以擷取 Java EE 應用程式相關的執行緒環境定義,並將它延伸至所排程作業的執行緒中。
關於這項作業
<featureManager>
<feature>concurrent-1.0</feature>
</featureManager>
執行緒環境定義的擷取和延伸是由環境定義服務管理。伺服器會建立環境定義服務 (DefaultContextService) 的預設實例,且該預設實例會配置成至少延伸 classloaderContext、jeeMetadataContext 和 securityContext。如果建立了 ManagedScheduledExecutorService,但沒有參照特定的環境定義服務實例,或沒有直接在其中配置環境定義服務實例,就會使用這個預設的環境定義服務實例。如需環境定義服務實例的相關資訊,請參閱「配置執行緒環境定義服務實例」主題。
預設的受管理排程執行程式實例 (DefaultManagedScheduledExecutorService) 是以 java:comp/DefaultManagedScheduledExecutorService 來提供,且會將預設的環境定義服務實例用於執行緒環境定義擷取和延伸之中。
程序
server.xml 檔中的配置範例:
範例
將受管理排程執行程式注入至應用程式元件(使用 @Resource),或是利用資源環境參照 (resource-env-ref) 來查閱。不論如何取得實例,都可以將它當作 javax.enterprise.concurrent.ManagedScheduledExecutorService 或下列任何超類別來以可交換方式使用:java.util.concurrent.ScheduledExecutorSerivce、java.util.concurrent.ExecutorService、javax.enterprise.concurrent.ManagedExecutorService
- 使用 @Resource 來注入成 java.util.concurrent.ScheduledExecutorService 的範例:
@Resource(lookup="concurrent/scheduledExecutor2") ScheduledExecutorService executor; ... // 將作業排程為從現在開始每半小時執行一次 Runnable updateSalesReport = new Runnable() { public void run() throws Exception { // 由於配置了 <jeeMetadataContext>,因此有可能進行 java:comp 查閱 DataSource ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/ds1"); ... query and update various database tables } }; ScheduledFuture<?> future = executor.scheduleAtFixedRate(updateSalesReport, 0, 30, TimeUnit.MINUTES);
- 使用 @Resource 來注入成 javax.enterprise.concurrent.ManagedScheduledExecutorService 的範例:
@Resource(lookup="concurrent/scheduledExecutor2") ManagedScheduledExecutorService executor; ... usage is same as previous example
- web.xml 檔中 java.util.concurrent.ScheduledExecutorService 的 <resource-env-ref> 範例:
<resource-env-ref> <resource-env-ref-name>concurrent/scheduledExecutor1</resource-env-ref-name> <resource-env-ref-type>java.util.concurrent.ScheduledExecutorService</resource-env-ref-type> </resource-env-ref>
- web.xml 檔中 javax.enterprise.concurrent.ManagedScheduledExecutorService 的 <resource-env-ref> 範例:
<resource-env-ref> <resource-env-ref-name>concurrent/scheduledExecutor2</resource-env-ref-name> <resource-env-ref-type>javax.enterprise.concurrent.ManagedScheduledExecutorService</resource-env-ref-type> </resource-env-ref>
- 使用資源環境參照的查閱範例:
ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService) new InitialContext().lookup("java:comp/env/concurrent/scheduledExecutor2"); executor.schedule(payrollTask, fridaysAtMidnightTrigger);