Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a constantly running process in JavaEE

How would you suggest to implement the following in JavaEE:

  1. I need to have a background process in the app server (I was thinking a stateful session beans) that constantly monitors "something" and if some conditions apply it does operations with the database.

  2. Most importantly it has to manipulated remotely by various clients.

So, basically, I need a process that will run constantly, keep its state and be open for method invocations by a number of remote clients.

Since I'm new to JavaEE I'm a bit confused which approach/"technology" to use. An help would be appreciated.

like image 552
Mr.Zeiss Avatar asked Apr 07 '13 07:04

Mr.Zeiss


People also ask

How do I stop a Java program from running in the background?

Click the "Processes" tab in the Task Manager window. Select the application name of your Web browser (or the Java program if running a standalone desktop version) in the Apps section of the Processes tab. Click the "End Task" button to stop the Java program and close the browser.


2 Answers

You can use a combination of a stateless session or singleton bean with an EJB timer an timer service. The bean would the interface used by the remote clients to control the background process. The timer service would periodically call back a method on the bean to verify the condition. The timers are automatically persisted by the EJB container, so they will do their job when your bean clients are disconnected.

Here is a sketch:

@Singleton
...
public TimerMangerbean implements TimerManager {

   @Resource
   private TimerService timerService;

   public void startMonitoring() {
      //start in 5 sec and timeout every 10 minutes
      Timer timer = timerService.createTimer(5000, 60000, "MyTimer");
   }

   public void stopMonitoring() {
      Collection<Timer> timers = timerService.getTimers();
      for(Timer timer : timers) {
         //look for your timer
         if("MyTimer".equals(timer.getInfo())) {
            timer.cancel();break;
         }
      }
   }

   //called every 10 minutes
   @Timeout
   public void onTimeout() {
      //verify the condition and do your processing
   }
}

See also: Using the timer service on Oracle JavaEE tutorial

like image 152
dcernahoschi Avatar answered Sep 21 '22 03:09

dcernahoschi


What about Quartz? See the links http://rwatsh.blogspot.com/2007/03/using-quartz-scheduler-in-java-ee-web.html http://lanbuithe.blogspot.com/2011/07/using-quartz-scheduler-in-java-ee-web.html http://www.mkyong.com/tutorials/quartz-scheduler-tutorial/

like image 43
StanislavL Avatar answered Sep 20 '22 03:09

StanislavL