How do you efficiently repeat an action every x mi

2020-04-07 03:05发布

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?

标签: java jboss
6条回答
Summer. ? 凉城
2楼-- · 2020-04-07 03:08

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

查看更多
3楼-- · 2020-04-07 03:12

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-04-07 03:14

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

查看更多
戒情不戒烟
5楼-- · 2020-04-07 03:18

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.

查看更多
ら.Afraid
6楼-- · 2020-04-07 03:25

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.

查看更多
趁早两清
7楼-- · 2020-04-07 03:30

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);
查看更多
登录 后发表回答