EJB3.0 定时服务:Timer Service

 

定时服务用作在一段特定的时间后执行某段程序

使用容器对象SessionContext创建定时器,并使用@Timeout 注释声明定时器方法

通过依赖注入@Resource SessionContext ctx,获得SessionContext对象,调用ctx.getTimerService().createTimer(Date arg0, long arg1, Serializable arg2)方法创建定时器,

当定时器创建完成后,还需声明定时器方法。定时器方法的声明很简单,只需在方法上面加入@Timeout 注释

package ejb;

public interface TimerTest {
 public void schedule(long m);
}

package ejb;

import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.annotation.Resource;
import java.util.Date;

import ejb.TimerTest;

@Remote(TimerTest.class)
public @Stateless class TimerTestBean implements TimerTest {
 private @Resource SessionContext ctx;
 private int count = 0;
 public void schedule(long m){
  ctx.getTimerService().createTimer((new Date(new Date().getTime() + m)),m,"我是一棵葱!");
 }
 
 @Timeout
 public void timeoutHandle(Timer timer){
  System.out.println(timer.getNextTimeout() + " " + count + " " + timer.getInfo());
  count ++;
  if(count > 5){
   System.out.println("Timer canceled!");
   timer.cancel();
   System.out.println("Timer canceled!");
  }
 }
}

 


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import = "ejb.*" %>
<%@ page import = "javax.naming.*" %>




Insert title here


<%
InitialContext ctx = new InitialContext();
TimerTest tt = (TimerTest) ctx.lookup("TimerTestBean/remote");
tt.schedule(3000l);
%>

你可能感兴趣的:(EJB3.0 定时服务:Timer Service)