如何只运行30分钟的java函数
我需要创建一个仅运行 30 分钟的 java 函数,并在 30 分钟结束时执行一些操作。但如果满足正确的条件,它也应该能够在给定时间之前自行终止。我不希望该函数处于休眠状态,因为它应该收集数据,因此没有休眠线程。
谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我需要创建一个仅运行 30 分钟的 java 函数,并在 30 分钟结束时执行一些操作。但如果满足正确的条件,它也应该能够在给定时间之前自行终止。我不希望该函数处于休眠状态,因为它应该收集数据,因此没有休眠线程。
谢谢
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
使用: Timer.schedule(TimerTask, long )
Use: Timer.schedule( TimerTask, long )
使用
System.currentTimeMillis()
获取开始时间,计算停止时间,并在收集想要收集的数据时不时检查当前时间。另一种方法是将计时器和数据收集解耦,以便它们每个都可以在自己的线程中运行。对于更具体的答案,如果您能告诉您正在收集什么数据以及您如何收集这些数据,将会很有帮助。
Get the start time with
System.currentTimeMillis()
, calculate the time when to stop and check the current time every now and then while you're collecting the data you want to collect. Another way would be to decouple the timer and the data collecting, so that each of them could run in their own threads.For a more specific answer, it would be helpful if you would tell what data you are collecting and how you are collecting it.
像这样的事情会起作用:
Something like this will work:
现代
java.util.concurrent
方式将使用ExecutorService
。有多个invoke
方法会超时。这是一个启动示例:
其中
Task
如下所示:另请参阅:
The modern
java.util.concurrent
way would be usingExecutorService
. There are severalinvoke
methods taking a timeout.Here's a kickoff example:
where
Task
look like this:See also: