我创建了一个计时器,当我部署我的应用程序时启动,我注意到这个计时器在Undeploy
我的应用程序时不会停止?
Undeploy
我的时候,我应该重启我的服务器吗?
应用的Singleton
@Singleton
@Startup
public class StartWhenDeploy {
private static final int PERIOD = 3000;
@PostConstruct
public void init() {
System.out.println("I will set information to start my task");
Timer timer = new Timer();
timer.schedule(new TimerAction(1), new Date(), PERIOD);
}
}
的TimerTask
public class TimerAction extends TimerTask {
public int nbrUsers;
public TimerAction(int nbrUsers) {
this.nbrUsers = nbrUsers;
}
@Override
public void run() {
System.out.println("This task is planified to execute at " + new Date());
System.out.println("Creation " + (createUser() ? "------------Success------------" : "------------Failed------------"));
}
public boolean createUser() {
try {
System.out.println("-------------->" + nbrUsers);
for (int i = 0; i < nbrUsers; i++) {
System.out.println("Create user >>>>" + i);
}
return true;
} catch (Exception e) {
System.out.println("Exception " + e);
return false;
}
}
}
它仍然在输出netbeans :
中显示了这样的结果...
Infos: This task is planified to execute at Wed Nov 16 14:40:29 GMT+01:00 2016
Infos: -------------->1
Infos: Create user >>>>0
Infos: Creation ------------Success------------
...
有人对这个问题有所了解吗?
谢谢。
答案 0 :(得分:1)
TimerTask生成一个新线程,其生命周期不受取消部署应用程序的影响。
更好的方法是使用@Schedule
@Singleton
@Startup
public class SimpleTimerBean {
static Logger logger = Logger.getLogger(SimpleTimerBean.class.getCanonicalName());
@Schedule(hour = "*", minute = "*", second = "*/3", info = "Create user every 3 seconds", timezone = "UTC")
public boolean createUser() {
try {
System.out.println("-------------->" + nbrUsers);
for (int i = 0; i < nbrUsers; i++) {
System.out.println("Create user >>>>" + i);
}
return true;
} catch (Exception e) {
System.out.println("Exception " + e);
return false;
}
}
}
之类的正确EJB计时器:
n <- 20
x <- rnorm(n)
y <- rnorm(n)
z <- x + y + rnorm(n)
m <- lm(z ~ x + y + I(y^2))
答案 1 :(得分:1)
在GlassFish中(通常在JavaEE中),您应该使用EJB规范中的TimerService
进行调度。我假设您正在使用java.util.Timer
,它只是在一个单独的线程中运行。 GlassFish对该线程一无所知,因此无法通过取消部署来阻止它。
您应该将您的Singleton重写为以下内容:
@Singleton
@Startup
public class StartWhenDeploy {
private static final int PERIOD = 3000;
// Inject the TimerService into this EJB
@Resource
private TimerService timer;
private TimerAction action;
@PostConstruct
public void init() {
System.out.println("I will set information to start my task");
// the action object is created before the timer
action = new TimerAction(1);
timer.createTimer(new Date(), PERIOD, "My timer");
}
// this method will be executed when the timer fires - it needs to wrap your `TimerAction` created once per this singleton instance (`TimerAction` does not have to extend `TimerTask` now)
@Timeout
public void runTimerAction() {
action.run();
}
}