我需要在 Java 中睡很长时间(几天)
我有一个应用程序需要按计划做一件事,而且只做一件事,并且它能够轻松计算出下次需要运行的时间。 从现在开始,它可能不需要在几天或几个月内运行此任务,但可能每隔几毫秒就会在其他方面处于活动状态。
我正在寻找一种简单的轻量级方法来安排该任务的运行。
I have an app that needs to do one thing, and one thing only, on a schedule and it will be able to calculate easily the time it next needs to run. It may not need to run this task for days or months from now, but will probably be active in every other respect every few milliseconds.
I'm looking for a simple lightweight approach to scheduling that one task to run.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 Unix 上,查看系统工具
cron
或at
。在 Windows 上,系统设置中有一个作业计划程序。
对于简单的仅 Java 解决方案,请尝试 定时器API。
对于更复杂的纯 Java 解决方案,请查看 quartz。
On Unix, have a look at the system tools
cron
orat
.On Windows, there is a job scheduler in the system settings.
For a simple Java-only solution, try the Timer API.
For a more complex Java-only solution, have a look at quartz.
如果您的 Java 应用程序打算连续运行,那么您可以使用 Timer< /a> 安排执行的类
如果您的应用程序不会连续运行,那么其他答案是正确的。 cron / 任务调度程序是可行的方法。
If your java app is intended to be running continuously then you can use the Timer class to schedule execution
If your app isn't going to be running continuously then the other answers are correct. cron / task scheduler are the way to go.
那么,如果您需要应用程序在特定时间运行,您可以安排 cron 作业。 或者,您可以编写一个简单的类,它将自行安排特定的时间。 由于我不知道那里有任何图书馆(从来没有真正需要寻找一个),所以我很久以前就写了一堂课来为自己安排任务。 希望它能有所帮助,大致上:
像这样扩展使用它:
Well, you can schedule a cron job if you need your app to run at certain times. Or, you can write a simple class that will schedule itself for certain times. Since I'm not aware of any library out there (never really needed to look for one), I wrote a class long ago to schedule a task for myself. Hope it helps and in ballpark:
Extend to use it like so:
Quartz 适合这种类型的事情。 Spring 应用程序也很好地支持它。
Quartz is good for this type of thing. It's supported well in Spring apps as well.
编写 Windows 服务(或 Linux 系统的守护程序)
以下是一些帮助您入门的链接:
Write a Windows Service (or a daemon for a linux box)
Here are some links to get you started :
只需使用java.util.concurrent,它有一个计划执行小部件。 您需要添加一个保护条件以防止过度运行,或者在当前执行的末尾添加下一个执行。
Just use java.util.concurrent, it has a scheduled execution widget. You'd need to add a guard condition to prevent excessive runs, or else add the next execution at the end of the current one.