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

使用容器对象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!");
  }
 }
}

 

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import = "ejb.*" %>
<%@ page import = "javax.naming.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<%
InitialContext ctx = new InitialContext();
TimerTest tt = (TimerTest) ctx.lookup("TimerTestBean/remote");
tt.schedule(3000l);
%>
</body>
</html>
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐