在Weblogic中使用定時器(commonj Timer for weblogic server)

1.簡介
  由於J2EE規範的限制,在Servlet和EJB中執行用戶自定義的多線程併發與定時器服務一直以來是困擾J2EE開發人員的一個大問題。現在CommonJ項目中的Work Manager和Timer規範將是解決這些問題的一個優秀方法。 
      CommonJ 定時器(Timer)規範提供了一個在Servlet和EJB中設置定時器的簡單方法,同時允許在Servlet和EJB中響應定時器的提醒。該規範提供了一個在不能或者不方便使用java.util.Timer環境中使用定時器功能的替代方法。

  現在在WebLogic Server 9.0中已經提供了對Work Manager和Timer規範的支持,在WebLogic Server 7和8中需要使用該項功能請參考這裏,xcommonj-work

  關於Work Manager和Timer規範的更多信息請訪問這裏:Timer and Work Manager for Application Servers

      在J2EE中使用 Work Manager 規範執行並行任務,請訪問這裏:http://dev2dev.bea.com.cn/techdoc/200508631.html

   Commonj定時器的參考請見這裏:http://dev2dev.bea.com.cn/techdoc/20051221711.html
2.定時器的使用辦法:
(1)在web.xml或者ejb-jar.xml中增加定時器的描述:
 <resource-ref>
    <res-ref-name>timer/MyTimer</res-ref-name>
    <res-type>commonj.timers.TimerManager</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Unshareable</res-sharing-scope>
  </resource-ref>
(2)定義定時器到時間的回調類:
import commonj.timers.*;
public class TestListener
    implements TimerListener
{
    public TestListener()
    {
    }
  
    public void timerExpired(Timer timer)
    {
        System.out.println("TimerExpired.");
    }
}
(3)在其它任何地方啓動定時器,並設置定時器的任務即可實現定時功能了。
       InitialContext ctx = new InitialContext();
            TimerManager mgr = (TimerManager)ctx.lookup("java:comp/env/timer/MyTimer");
            TimerListener listener = new TestListener();
            mgr.schedule(listener,4000);//定時器執行一次
            mgr.scheduleAtFixedRate(listener,5000,2000);//定時器週期執行
            //按照日曆來執行定時器
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR, 12);
            mgr.schedule(listener, cal.getTime());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章