在 Java EE 应用程序中使用 Thread.sleep()、定时器或平台 cron 作业进行定期操作

发布于 2024-12-21 14:22:38 字数 267 浏览 1 评论 0原文

我有一个 Java EE 应用程序,每十五分钟从互联网下载一次股票价格。从计时准确性的角度来看,应用程序最好将这种周期性操作内部化,即使用 Thread.sleep() 与计数器结合使用或设置计时器,或者通过以下方式公开任务会更好吗一个 URL 并让平台 cron 作业定期访问该 URL(当然以所需的频率)。

两种方法的优缺点是什么?

我看到针对 OpenJDK 实现报告的计时器错误,这让我感到震惊。该错误指出,系统时间的变化会影响与时间相关的操作和方法的运行,例如睡眠和定时器周期。

I have a Java EE application which downloads stock prices from the internet every fifteen minutes. From a timing accuracy perspective is is best for the application to internalise this periodic operation i.e. use Thread.sleep() in combination with a counter or set up a timer Or would it be better to expose the task via a URL and have a platform cron job hit the URL periodically (at the the required frequency of course).

What are the pros and cons of both approaches?

I've been spooked by a timer bug I saw reported against the OpenJDK implementation. The bug stated that changes in the system time affected the operation of the time related operations and methods such as sleep and timer periodicity.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小伙你站住 2024-12-28 14:22:38

Timer 并未被弃用,但现在存在更好的替代方案:SheduledExecutorService。它的优点之一是它使用相对时间而不是绝对时间来进行调度。

恕我直言,使用外部 cron 脚本或内部计时器只是一个问题或偏好。内部计时器更容易设置,但如果您已经有其他 crons,您可能需要使用另一个 cron 并将此责任放在一个位置。

Timer is not deprecated, but a better alternative now exists: SheduledExecutorService. One of what makes it better is that it uses relative time rather than absolute time for scheduling.

Using an external cron script or an internal timer is just a matter or preference, IMHO. An internal timer is easier to setup, but if you already have other crons in place, you might want to use an additional one and have this responsibility in a single place.

路弥 2024-12-28 14:22:38

一定要考虑使用为该任务构建的调度作业。尝试将任务本身与任何时间考虑因素分开。

  • 正如所建议的,石英是一个不错的选择。
  • Cron 还不错,但需要更多设置才能与您的集成
    任务。
  • 如果在 Java EE 上,您可以使用 EJB 计时器。
  • 您可以使用 ScheduledExecutorService 自行推出(不推荐)

Definitely consider using a scheduling job that was built for the task. Try and split the task itself from any timing considerations.

  • As was suggested, Quartz is a good choice.
  • Cron is not bad, but would require more setup to integrate with your
    task.
  • If on Java EE you can use an EJB timer.
  • You can roll your own with ScheduledExecutorService (not recommended)
心凉 2024-12-28 14:22:38

Thread.sleep 不是定期执行代码的推荐方法。这是不准确的,通常是糟糕设计的标志。我建议您使用 Timer 类轻松地定期安排代码的执行。

Thread.sleep is not a recommended way to execute code periodically. It's inaccurate and usually a sign of bad design. I suggest you use the Timer class to easily schedule the execution of code periodically.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文