tags:

views:

170

answers:

6

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?

+5  A: 

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

abyx
Thanks a lot - and to everyone else. I used the Timer / TimerTask examples and they appear to have worked a treat!
thickosticko
A: 

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.

Chris
+8  A: 

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.

Poindexter
A: 

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

JuanZe
+5  A: 

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);
Adamski
A: 

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.

Yishai