在我的 scheduleAtFixedRate 方法中,我设置了延迟时间来启动 运行 该方法。但是这个延迟时间不能立即生效运行

In my scheduleAtFixedRate method, I put delay time to start run the method. But this delay time cannot work and run immediatly

这是我的代码,

static ScheduledExecutorService scheduler = null;
scheduler.scheduleAtFixedRate(new Testing(),60, 24*60*60,TimeUnit.SECONDS);


public static Runnable Testing()
{ System.out.println("Testing...");
}

我想在 60 秒后调用 Runnable() 方法,但是当我 运行 代码时它会立即调用这个方法。 我的代码有什么问题吗? 我是 scheduleAtFixedRate 方法的新手。 谢谢:)

请试试这个

scheduler.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    System.out.println("Testing...");
  }
}, 60, 24*60*60,TimeUnit.SECONDS);

创建一个扩展 Runnable 的 class。

  static class MyRunnable implements Runnable {
    public void run() {
      System.out.println(i + " : Testing ... Current timestamp: " + new Date());
      // Put any relevant code here.
    }
  }

那么您的代码将按预期工作。在 codiva.io online compiler ide 处尝试 运行 获取完整的工作代码。

一个相关的建议,在专业代码中,人们通常避免使用线程调度程序来 运行 每天 运行 的任务。最常见的选择是使用 cron 作业和更多设置。但这超出了这个问题的范围。

Runnable 是一个接口,您必须实现 运行() 方法。您可以尝试将代码更改为



    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println("Testing...");
        }
    },60, 24*60*60,TimeUnit.SECONDS);