[英]Running a Java Thread in intervals
I have a thread that needs to be executed every 10 seconds. 我有一个需要每10秒执行一次的线程。 This thread contains several calls (12 - 15) to a database on another server.
该线程包含对另一台服务器上的数据库的多次调用(12-15)。 Additionally, it also accesses around 3 files.
此外,它还可以访问大约3个文件。 Consequently, there will be quite a lot of IO and network overhead.
因此,将会有相当多的IO和网络开销。
What is the best strategy to perform the above? 执行上述操作的最佳策略是什么?
One way would be to use the sleep method along with a while loop, but that would be a bad design. 一种方法是使用sleep方法和while循环,但这将是一个糟糕的设计。
Will a class similar to Timer be helpful in this case? 在这种情况下,类似于Timer的类会有用吗? Also, would it be better to create a couple of more threads (one for IO and one for JDBC), instead of having them run in one thread?
另外,最好是创建几个线程(一个用于IO,一个用于JDBC),而不是让它们在一个线程中运行?
I find that a ScheduledExecutorService is an excellent way to do this. 我发现ScheduledExecutorService是一种很好的方法。 It is arguably slightly more complex than a
Timer
, but gives more flexibility in exchange (eg you could choose to use a single thread or a thread pool; it takes units other than solely milliseconds). 它可以说比
Timer
更复杂,但在交换中提供了更大的灵活性(例如,您可以选择使用单个线程或线程池;它只需要毫秒以外的单位)。
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
Runnable periodicTask = new Runnable() {
public void run() {
// Invoke method(s) to do the work
doPeriodicWork();
}
};
executor.scheduleAtFixedRate(periodicTask, 0, 10, TimeUnit.SECONDS);
Have a look at the Timer and TimerTask classes. 看看Timer和TimerTask类。 They are exactly what you want.
它们正是你想要的。
You can make a TimerTask implementation that takes your thread object in a constructor. 您可以创建一个TimerTask实现,将您的线程对象置于构造函数中。
The run method will then call the threads run method. 然后run方法将调用threads run方法。
// Perhaps something like this
Timer t = new Timer();
t.scheduleAtFixedRate(yourTimerTask, 0, 10 * 1000);
// Hopefully your task takes less than 12 seconds
One option is to create a ScheduledExecutorService to which you can then schedule your job: 一种选择是创建一个ScheduledExecutorService,然后您可以安排您的工作:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleWithFixedDelay(...);
If you did decide to have multiple threads, then you can create a ScheduledExecutorService with more threads (again, via the Executors class). 如果您确定拥有多个线程,那么您可以创建一个包含更多线程的ScheduledExecutorService(同样,通过Executors类)。
In terms of how many threads and what you put in each thread, in terms of performance, I'd say this depends on: 就每个线程中的线程数和内容而言,就性能而言,我认为这取决于:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.