介绍:
定时器分为两种:single-action Timer(单动定时器)和interval Timer(间隔定时器)。
为了使用定时服务,1.enterprise bean必须实现javax.ejb.TimedObject接口,该接口定义了一个回调方法,ejbTimeout().
package javax.ejb;
public interface TimedObject{
public void ejbTimeout(Timer timer);
}
2.在EJB3.0中,还可以使用@javax.ejb.Timeout注解来指定回调方法。此方法必须返回void,并接受一个javax.ejb.Timer类型的参数。
开发者有3种获得TimerService对象的可用方式。
1.通过EJBContext获得TimerService实例。
2.使用JNDI API查找到TimerService对象,从而能够访问到定时器服务。
3.还可以借助于依赖注入 获得TimerService对象,
@Resource javax.ejb.TimerService timerService。
TimeService接口为enterprise bean 访问EJB容器的定时服务提供 了支持,利用它可以创建新的定时器,列出已有的定时器。
优点:
1.EJB定时器服务提供的任务调度语义与平台无关。
2.EJB定时器服务允许开发者通过编程实现定时器的定义和设定。
3.最后,同Flux或Quartz相比,EJB定时器服务提供了标准化接口。
缺点:
1.EJB规范不支持在部署描述符或Annotation注释中声明Timer间隔。
2.EJB定时器服务中的定时器的使用不够灵活。定时器API仅能处理单位为毫秒的时间。如果能够依据小时、日、月方式指定定时器的行为,则EJB定时器服务的使用也将变的更加容易。
package ejb_jms;
import javax.jms.JMSException;
public interface HelloWorld {
public void sendMessage(String time)throws JMSException;
}
@Stateless
@Remote( { HelloWorld.class })
@Local( { HelloWorld.class })
@RemoteBinding(jndiBinding = "byc:/ejb3/helloworld")
public class HelloWorldBean implements HelloWorld {
@Resource(mappedName = "byc:/ejb3/MyAccountBean")
MyAccount Rcount;
public void sendMessage(String time) throws JMSException {
System.out.println("sendMessage====");
Hashtable ht = new Hashtable();
ht.put("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
ht.put("java.naming.factory.url.pkgs", "org.jboss.naming");
ht.put("java.naming.provider.url", "jnp://localhost:1099");
ConnectionFactory cf = null;
Topic topic = null;
TopicConnectionFactory tcf = null;
TopicConnection tc = null;
TopicSession ts = null;
TopicPublisher tp = null;
ObjectMessage mmsg = null;
try {
Context ctx = new InitialContext(ht);
//找到工厂类
cf = (ConnectionFactory) ctx.lookup("ConnectionFactory");
tcf = (TopicConnectionFactory) cf;
topic = (Topic) ctx.lookup("topic/IPMACTopic");
//获取连接
tc = tcf.createTopicConnection();
ts = tc.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
//获取发布相当与session
tp = ts.createPublisher(topic);
} catch (NamingException e1) {
// TODO Auto-generated catch block
System.out.println("sendMessage ==发送消息创建失败====");
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println("sendMessage ==发送消息创建失败===2=");
}
// 在这里发消息
try {
// 消息类别共三种
mmsg = ts.createObjectMessage();
// 设置MapMassge的主题
mmsg.setJMSType("example");//主题
//内容
mmsg.setObject(time);
// 发布JMS消息;
tp.send(mmsg);
System.out.println("发送成功====");
} catch (JMSException e) {
System.out.println("sendMessage ==jms发送消息失败====");
e.getStackTrace();
} finally {
//关闭资源
if (tp != null) {
tp.close();
}
if (ts != null) {
ts.close();
}
if (tc != null) {
tc.close();
}
}
}
}
@Stateless
@Remote( { TimerService.class })
@Local( { TimerService.class })
@RemoteBinding(jndiBinding = "byc:/ejb3/TimerServiceBean")
public class TimerServiceBean implements TimerService {
@EJB(beanName = "HelloWorldBean")
HelloWorld HelloWorldBean;
private int count = 1;
private @Resource
SessionContext ctx;// 通过@Resource获取jndi上的SessionContext对象
String name = "gaochong";
public void scheduleTimer(long milliseconds) {
count = 1;
ctx.getTimerService().createTimer(
new Date(new Date().getTime() + milliseconds), milliseconds,
"大家好,这是我的第一个定时器");
}
@Timeout
public void timeoutHandler(Timer timer) throws JMSException {
System.out.println("---------------------");
System.out.println("定时器事件发生");
System.out.println("---------------------");
if (count >= 5) {
timer.cancel();// 如果定时器触发5次,便终止定时器
}
HelloWorldBean.sendMessage(name);
count++;
}
}
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),//javax.jms.Queue 类型
@ActivationConfigProperty(propertyName = "destination", propertyValue = "topic/IPMACTopic") //位置
})
public class PrintBean implements MessageListener {
public void onMessage(Message msg) {
try {
if (msg instanceof MapMessage) {
System.out.println("MapMessage example....");
MapMessage mmsg = (MapMessage) msg;
String jmstype = null;
jmstype = mmsg.getJMSType();
if (jmstype != null && jmstype.equals("alarm_original")) {
System.out.println("JMSType:" + mmsg.getJMSType());
System.out.println("message:" + mmsg.getString("detail"));
}
else {
System.out.println(mmsg.getJMSType() + " is null");
}
}
if (msg instanceof ObjectMessage) {
System.out.println("ObjectMessage example....");
ObjectMessage mmsg = (ObjectMessage) msg;
String jmstype = null;
jmstype = mmsg.getJMSType();
if (jmstype != null && jmstype.equals("example")) {
long time = System.currentTimeMillis();
Object o = (String) mmsg.getObject();
System.out.println("接收...." + o.toString());
}
}
if (msg instanceof MapMessage) {
System.out.println("MapMessage example....");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String args[]) throws NamingException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
InitialContext ctx = new InitialContext(props);// 客户端和jboss运行在同一个jvm,不需要传入props
HelloWorld helloworld = (HelloWorld) ctx.lookup("byc:/ejb3/helloworld");
TimerService timer=(TimerService) ctx.lookup("byc:/ejb3/TimerServiceBean");
timer.scheduleTimer(8000);
}
}