简体   繁体   English

你如何每x分钟有效地重复一次动作?

[英]How do you efficiently repeat an action every x minutes?

I have an application that runs in JBoss. 我有一个在JBoss中运行的应用程序。 I have an incoming web service request that will update an ArrayList . 我有一个传入的Web服务请求将更新ArrayList I want to poll this list from another class every 60 seconds. 我想每隔60秒从另一个班级轮询这个列表。 What would be the most efficient way of doing this? 这样做最有效的方法是什么?

Could anyone point me to a good example? 有谁能指出我一个很好的例子?

I would also recommend ScheduledExecutorService , which offers increased flexibility over Timer and TimerTask including the ability to configure the service with multiple threads. 我还建议使用ScheduledExecutorService ,它提供了比TimerTimerTask更高的灵活性,包括使用多个线程配置服务的能力。 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);

As abyx posted, Timer and TimerTask are a good lightweight solution to running a class at a certain interval. 正如abyx发布的那样, TimerTimerTask是一个很好的轻量级解决方案,可以在一定的时间间隔内运行类。 If you need a heavy duty scheduler, may I suggest Quartz . 如果你需要一个重型调度程序,我可以建议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. 就像我说的那样,这可能对你的情况有点过分了。

You can use Timer and TimerTask . 您可以使用TimerTimerTask An example is shown here . 这里显示一个例子。

See java.util.Timer . 请参阅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. 当你的应用程序启动并让它进行轮询时,你需要在一个单独的线程中启动一个机器人。

检查问题“如何每天从Java运行任务”的答案,以获取与您的问题相关的资源列表。

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. 没有错,但它不符合EJB规范。 If that is a problem, you can use JBoss' timer facilities. 如果这是一个问题,你可以使用JBoss的计时器工具。 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. 但是,如果EJB规范存在争议,那么像ArrayList这样的存储状态也不合规,所以如果你只是想读一些静态变量,特别是使用容器定时服务可能有点过分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM