简体   繁体   English

Java ScheduledExecutorService在幕后

[英]Java ScheduledExecutorService behind the scenes

How does things like scheduleAtFixedRate work? scheduleAtFixedRate东西如何工作? How does it work behind the scenes and is there a penalty to using it? 它在后台如何工作?使用它会受到惩罚吗?

More specifically, I have a task that I want to run periodically, say every 12 hours. 更具体地说,我有一个要定期运行的任务,例如每12小时运行一次。 The period is not strict at all, so my first instinct was to check in every request (tomcat server) if it's been more than >12 hours since the task last executed and if so, execute it and reset the timer. 这个时间段并不严格,所以我的第一个直觉是检查每个请求(tomcat服务器)是否距离任务上次执行已超过12小时,如果是,则执行该任务并重置计时器。 The downside of this is that I have to do a small time check on every request, make sure the task is run only once (using a semaphore or something similar) and the task might not execute in a long time if there's no requests. 这样做的缺点是我必须对每个请求进行一次小的时间检查,确保任务仅运行一次(使用信号量或类似方法),并且如果没有请求,任务可能不会长时间执行。

scheduleAtFixedRate makes it easier to schedule a recurring task, but since I don't know how it does it, I don't know what the performance impact is. scheduleAtFixedRate使计划重复执行的任务变得更加容易,但是由于我不知道它是如何执行的,因此我不知道对性能的影响。 Is there a thread continually checking if the task is due to run? 是否有一个线程不断检查任务是否应运行? etc. 等等

edit: In Timer.java , there's a mainLoop function which, in my understanding, is something like this (overly simplified): 编辑:Timer.java ,有一个mainLoop函数,据我所知,就是这样(过于简化):

while(true) {
    currentTime = System.currentTimeMillis();
    if(myTask.nextExecutionTime == currentTime) myTask.run();
}

Won't this loop try to run as fast as possible and use a ton of CPU (I know, obviously not, but why )? 这个循环是否会尝试尽可能快地运行并使用大量CPU(我知道,显然不是,但是为什么 )? There's no Thread.sleep in there to slow things down. 那里没有Thread.sleep来减慢速度。

You can read the code if you wish to work out how it works. 如果您想了解代码的工作原理,则可以阅读它。

There is an overhead using ScheduledExecutorService in terms of CPU and memory, however on the scale of hours, minutes, second even milli-seconds, it probably not work worrying about. 使用ScheduledExecutorService会产生CPU和内存方面的开销,但是就小时,分钟,秒甚至毫秒的规模而言,它可能无法正常工作。 If you have a task running in the range of micro-seconds, I would consider something more light weight. 如果您的任务在微秒内运行,我会考虑减轻重量。

In short, the overhead is probably too small for you to notice. 简而言之,开销可能太小了,您无法注意到。 The benefit it gives you is ease of use, and it is likely to be worth it. 它给您带来的好处是易于使用,并且可能值得。

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

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