1. 创建一个Session Bean
2. 注入SessionContext Resource
3. 构造一个Timer
4. 利用@Timeout注解定义定时任务的具体执行
package com.icode.jejb.time;
/**
* Created with IntelliJ IDEA.
* User: alexz
* Date: 14-6-25
* Time: 下午4:44
* To change this template use File | Settings | File Templates.
*/
public interface TimerTask {
void start();
}
package com.icode.jejb.time;
import javax.annotation.Resource;
import javax.ejb.*;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: alexz
* Date: 14-6-25
* Time: 下午4:44
* To change this template use File | Settings | File Templates.
*/
@Stateless
@Remote(value = TimerTask.class)
public class SimpleTimerTask implements TimerTask {
private int count = 0;
@Resource
private SessionContext sessionContext;
public SimpleTimerTask() {
System.out.println("Instance the SimpleTimerTask Bean!!!!!!!!!!!!!");
}
@Timeout
public void execute(Timer timer) {
String params = (String) timer.getInfo();
System.out.println(count + ": " + params);
count++;
}
@Override
public void start() {
TimerService timerService = sessionContext.getTimerService();
timerService.createTimer(new Date(new Date().getTime() + 2000), 3000, "This is my first timer task!!!");
}
}