将 Java 任务安排在指定时间
我希望能够在 Java 中在特定时间安排任务。我知道 ExecutorService 能够定期在指定的延迟后进行调度,但我更多的是在一天中的某个时间而不是在一段持续时间之后进行调度。
有没有办法让 Runnable
在 2:00 执行,或者我是否需要计算从现在到 2:00 之间的时间,然后安排可运行在该延迟之后执行?
I would like to be able to schedule a task at a specific time in Java. I understand that the ExecutorService
has the ability to schedule at periodic intervals, and after a specified delay, but I am looking more for a time of day as opposed to after a duration.
Is there a way to have, say, a Runnable
execute at 2:00, or do I need to calculate the time between now and 2:00, and then schedule the runnable to execute after that delay?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
查看 Quartz。我们将它用于我们的生产应用程序,它非常好。它的工作原理与 crontab 非常相似。您可以在设定的计划中指定一个时间,它将在那时执行回调。
Check out Quartz. We use it for our production apps, and it's very good. It works pretty much like crontab. You can specify a time during a set schedule and it'll execute a callback at that time.
用户
java.util.Timer
。它有方法 newschedule(task, time)
,其中 time 是您想要执行一次任务的日期。user
java.util.Timer
. It has method newschedule(task, time)
where time is a Date when you want to execute the task once.您也可以使用 spring 注释
http:// /static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
you can use spring annotations too
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
这就是我使用 java7SE 解决它的方法:
它恰好比我想象的正确执行更棘手
this is how I've solved it using java7SE:
it happens to be trickier than I thought to do it correctly
您将需要 Quartz。
You'll be wanting Quartz.
今天早上我遇到了这种情况......这是我在午夜运行的代码
Got myself on this situation this morning... This was my code to run at midnight