4

I am planning to use this to poll a database which can take close to 10-15 minutes or more, so should I be using timers for this.

4

7 回答 7

8

If you want the task to complete quickly but what you need to do actually takes longer, you could split it up into two pieces. Have one that runs when the Timer fires, so you get things happening at the right time, but then defer the serious processing to another function (say, in a different thread) that can take as long as it needs. From the API, the problem with Timer tasks taking too long is that they hog the thread, possibly delaying subsequent tasks, so moving the time-consuming processing to another thread should avoid that problem. To answer the question in your title, "quickly" would mean "it should finish before the Timer needs to fire again".

于 2008-12-05T04:26:54.787 回答
4

I'm assuming you talking about the java.util.Timer, not the Swing specific ones?

If I remember correctly, that timer simply defers execution to a single background thread that essentially serves every timer instance in the JVM, so the problem could be that one timer hogs that thread for every other timer.

So quickly would depend on the rest of your application and whether you use other timers.

Generally, I avoid using it for anything serious, or I just have it spawn a new thread.

于 2008-12-05T04:20:38.073 回答
3

尽管如果您从计时器任务中生成一个线程来完成工作,请注意时间触发速度比线程完成速度更快的情况,从而导致工作量不断下降。

于 2008-12-05T04:37:44.267 回答
1

java.util.concurrent.ScheduledThreadPoolExecutor是“新java.util.Timer”。您可以拥有多个(一个池)线程,因此您可以容纳长时间运行的任务。即便如此,您可能需要考虑检查是否重叠太多。

当然,您可以拥有多个Timers,并TimerTask适当地分配您的 s。

于 2008-12-05T13:07:09.913 回答
1

The timer TASK should execute quickly, the polling interval is irrelevant to its usage. Make sure you aren't confusing the two.

于 2008-12-05T04:24:48.783 回答
1

在这种情况下,这意味着您必须在下一个计时器事件发生之前完成您的工作,否则将不会处理下一个事件。由于计时器类是全局的,因此您永远无法确定还有谁在使用它(例如,您的数据库驱动程序可能正在使用它来实现超时)。

如果您必须做长时间的工作,请使用计时器“启动”另一个线程(将项目添加到工作队列或在计时器事件处理程序中启动第二个线程)。这将快速释放下一个事件的计时器。

于 2008-12-05T11:29:37.383 回答
0

The answer is, it depends. If you are only going to have this one polling task run, and the interval is more than sufficient for each run to finish before the next one begins, then this solutions will work fine.

The problem is when there is more than one TimeTask on the same Timer, since they execute sequentially on the same thread. Therefore a long running task would cause the other tasks to wait for long periods of time, which defeats the purpose of creating timed tasks.

There are better solutions for the more complex scenario in the java.util.concurrent package as well as other libraries like Quartz.

于 2008-12-05T14:32:27.683 回答