在 java 中创建间隔
Creating an interval in java
我需要在我的 java 项目中每 10 秒 运行 一个函数。
我希望它像一个无限循环但不使用 while(true) 或 thread.sleep...
有什么想法吗?
您可以使用 Timer 方法:
Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
这里,task
是你要执行的任务(派生自TimerTask
),period
是两个任务执行之间的时间间隔,delay
是以毫秒为单位的延迟 before 每次执行。
这或多或少是 Making a Thread to Sleep for 30 minutes. That question mentions the ScheduledExecutorService
, which I've used and been very happy with. It's a bit heavyweight, so Timer may be all that you need. The Java Tutorial 的副本,有一个很好的例子说明如何使用它。
我需要在我的 java 项目中每 10 秒 运行 一个函数。 我希望它像一个无限循环但不使用 while(true) 或 thread.sleep...
有什么想法吗?
您可以使用 Timer 方法:
Timer.scheduleAtFixedRate(TimerTask task, long delay, long period)
这里,task
是你要执行的任务(派生自TimerTask
),period
是两个任务执行之间的时间间隔,delay
是以毫秒为单位的延迟 before 每次执行。
这或多或少是 Making a Thread to Sleep for 30 minutes. That question mentions the ScheduledExecutorService
, which I've used and been very happy with. It's a bit heavyweight, so Timer may be all that you need. The Java Tutorial 的副本,有一个很好的例子说明如何使用它。