由于J2EE規(guī)范的限制,在Servlet和EJB中執(zhí)行用戶自定義的多線程并發(fā)與定時(shí)器服務(wù)一直以來是困擾J2EE開發(fā)人員的一個(gè)大問題?,F(xiàn)在CommonJ項(xiàng)目中的Work Manager和Timer規(guī)范將是解決這些問題的一個(gè)優(yōu)秀方法?!?/div>
CommonJ 定時(shí)器(Timer)規(guī)范提供了一個(gè)在Servlet和EJB中設(shè)置定時(shí)器的簡(jiǎn)單方法,同時(shí)答應(yīng)在Servlet和EJB中響應(yīng)定時(shí)器的提醒。該規(guī)范提供了一個(gè)在不能或者不方便使用
java.util.Timer環(huán)境中使用定時(shí)器功能的替代方法。
現(xiàn)在在WebLogic Server 9.0中已經(jīng)提供了對(duì)Work Manager和Timer規(guī)范的支持,在WebLogic Server 7和8中需要使用該項(xiàng)功能請(qǐng)參考這里,xcommonj-work。
關(guān)于Work Manager和Timer規(guī)范的更多信息請(qǐng)?jiān)L問這里:Timer and Work Manager for application Servers。
在J2EE中使用 Work Manager 規(guī)范執(zhí)行并行任務(wù),請(qǐng)?jiān)L問這里:http://dev2dev.bea.com.cn/techdoc/200508631.Html
Commonj定時(shí)器的參考請(qǐng)見這里:http://dev2dev.bea.com.cn/techdoc/20051221711.html
2.定時(shí)器的使用辦法:
(1)在web.
xml或者ejb-jar.xml中增加定時(shí)器的描述:
<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)定義定時(shí)器到時(shí)間的回調(diào)類:
import commonj.timers.*;
public class TestListener
implements TimerListener
{
public TestListener()
{
}
public void timerEXPired(Timer timer)
{
System.out.
PRintln("TimerExpired.");
}
}
(3)在其它任何地方啟動(dòng)定時(shí)器,并設(shè)置定時(shí)器的任務(wù)即可實(shí)現(xiàn)定時(shí)功能了。
InitialContext ctx = new InitialContext();
TimerManager mgr = (TimerManager)ctx.lookup("java:comp/env/timer/MyTimer");
TimerListener listener = new TestListener();
mgr.schedule(listener,4000);//定時(shí)器執(zhí)行一次
mgr.scheduleAtFixedRate(listener,5000,2000);//定時(shí)器周期執(zhí)行
//按照日歷來執(zhí)行定時(shí)器
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 12);
mgr.schedule(listener, cal.getTime());