Java延迟函数

Java delay function

BuzzerControl函数是使蜂鸣器发声的函数。我希望这个功能每三秒闪烁一次。我应该怎么办?我尝试了休眠功能,但它不起作用。

While(true){
 BuzData=1;
 BuzzerControl(BuzData);
}

首先,我们需要一个 Handler 在 3000 毫秒后启动 Runnable,即 3 秒

private Handler handler = new Handler();
handler.postDelayed(runnable, 3000);

而且我们还需要 Handler 的 Runnable

private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      /* do what you need to do */
      foobar();
      /* and here comes the "trick" */
      handler.postDelayed(this, 3000);
   }

Note:There’s also another advantage of this solution: You don’t have to create new Timer(Task)s all the time and can reuse the one Handler and Runnable.