Tutorial :How do you efficiently repeat an action every x minutes?



Question:

I have an application that runs in JBoss. I have an incoming web service request that will update an ArrayList. I want to poll this list from another class every 60 seconds. What would be the most efficient way of doing this?

Could anyone point me to a good example?


Solution:1

I would also recommend ScheduledExecutorService, which offers increased flexibility over Timer and TimerTask including the ability to configure the service with multiple threads. This means that if a specific task takes a long time to run it will not prevent other tasks from commencing.

// Create a service with 3 threads.  ScheduledExecutorService execService = Executors.newScheduledThreadPool(3);    // Schedule a task to run every 5 seconds with no initial delay.  execService.scheduleAtFixedRate(new Runnable() {    public void run() {      System.err.println("Hello, World");    }  }, 0L, 5L, TimeUnit.SECONDS);  


Solution:2

As abyx posted, Timer and TimerTask are a good lightweight solution to running a class at a certain interval. If you need a heavy duty scheduler, may I suggest Quartz. It is an enterprise level job scheduler. It can easily handle thousands of scheduled jobs. Like I said, this might be overkill for your situation though.


Solution:3

You can use Timer and TimerTask. An example is shown here.


Solution:4

See java.util.Timer. You'll need to start a robot in a separate thread when your app comes up and have it do the polling.


Solution:5

Check the answers to the question "How to run a task daily from Java" for a list of resources related to your problem.


Solution:6

The other answers are basically advising you do your own threads. Nothing wrong with that, but it isn't in conformance with the EJB spec. If that is a problem, you can use JBoss' timer facilities. Here is an example of how to do that.

However, if the EJB spec is at issue, storing state like an ArrayList isn't compliant as well, so if you are just reading some static variable anyway, specifically using a container Timer service is likely overkill.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »