In Java EE I used the EJB Timer Service to schedule a Task:
@Stateless
public class TestSchedule {
@Schedule(second = "*/30", minute = "*", hour = "*")
public void processFiles() {
}
}
As this approach is not supported in Eclipse Micro Profile...how is the common way to realize this?
Using EJB timers
If you are using WebSphere Liberty or OpenLiberty you can simply enable the ejbLite-3.2
feature in your server.xml to just pull in EJB Lite functionality (including non-persistent EJB timers):
<featureManager>
<feature>ejbLite-3.2</feature>
</feature>
If you want persistent EJB timers, you can enable the full ejb-3.2
feature.
Note that the code you have posted in the original question is from JavaEE, not MicroProfile, but Liberty servers do support using JavaEE and MicroProfile technologies together in the same server.
Using Java EE Concurrency
Another more modern/lightweight alternative to non-persistent EJB timers is JavaEE Concurrency utilties. This can be enabled with the concurrent-1.0
feature in server.xml:
<featureManager>
<feature>concurrent-1.0</feature>
</featureManager>
To use it, you can submit a Callable
or Runnable
object to a ManagedScheduledExecutorService
like this:
@Resource
ManagedScheduledExecutorService exec;
// ...
public void startWork() {
// Use a Java 8 lambda to define the Runnable
exec.scheduleAtFixedRate(() -> {
System.out.println("This will run every 30 seconds.");
}, 30, TimeUnit.SECONDS);
}
If you are just starting to write this application, I would recommend using Java EE Concurrency Utilities over EJB timers, since EE Concurrency is more lightweight, and MicroProfile is currently looking to incorporate similar functionality with a MicroProfile Concurrency project. However, if you need to use persistent tasks, then go with EJB timers.