Reputation: 211
I am trying to use the ScheduledExecutorService to run every few seconds in EJB. However, it does seem to work. I am not sure if I am doing anything wrong. I found this website: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html.
I want to run some code every few seconds. I am not sure whether this is concurrency because I want to execute only on one Thread that runs repeately. Below is the code:
@Startup
@Singleton
public class StartUp {
private ScheduledExecutorService executor;
@PostConstruct
public void start() {
executor = Executors.newScheduledThreadPool(1);
Runnable runnable = new Runnable() {
public void run() {
while(true) {
System.out.println("i");
// after send an e-mail
}
}
};
ScheduledFuture<?> scheduledFuture = executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
}
}
This does not seem to run. What am I doing wrong?
Any ideas?
Upvotes: 1
Views: 1389
Reputation: 1947
When using EJBs you shouldn't create your own thread pool, but let the container do that for you. You should have something similar to:
@Singleton
public class TimerService {
@EJB
HelloService helloService;
@Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println("timer: " + helloService.sayHello());
}
}
Upvotes: 3