【问题标题】:Perform a task each interval每个间隔执行一个任务
【发布时间】:2015-06-08 22:27:57
【问题描述】:

所以我试图安排一个时间实例,它每 10 秒重复一次。现在我有一些东西可以在 10 秒后完成一项任务,但是我该如何让它在这样做后重置。

this.schedule = TimerManager.getInstance().schedule(new Runnable() {
        @Override
        public void run() {
            chrs.get(0).getMap().spawnMonsterOnGroudBelow(MapleLifeFactory.getMonster(100100), chrs.get(0).getPosition());
        }

    }, time);

}

时间等于 10000 毫秒,因此是 10 秒。

【问题讨论】:

  • "...but how do I make it so that it resets after doing so." -- “重置”这个词是什么意思?
  • 抱歉,选词不当。我只是想让事件在每个给定的时间间隔重新发生。

标签: java time schedule


【解决方案1】:

1) 创建ScheduledExecutorService

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

2) 创建和安排您的 Runnable:

Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("Done:" + new Date(System.currentTimeMillis()));
        // some long task can be here
        executor.schedule(this, 10, TimeUnit.SECONDS);
    }
};
//can be 0 if you want to run it fist time without 10 sec delay
executor.schedule(task, 10, TimeUnit.SECONDS); 

如果您不关心可运行的持续时间并且总是希望每 10 秒触发一次事件

executor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println("Done:" + new Date(System.currentTimeMillis()));
    }
}, /* same, can be 0*/ 10 , 10, TimeUnit.SECONDS);

3) 退出程序时使用这个

executor.shutdown();

【讨论】:

  • 如果我将包含此代码的类实例设置为null,执行器会关闭吗?
  • 不。您必须先将其关闭 executor.shutdown();executor.shutdownNow();
  • 两者有什么区别?
  • 非常感谢。你真的很有帮助而且简洁。
【解决方案2】:

【讨论】:

    【解决方案3】:

    您可以改用 scheduleAtFixedRate 方法。

    看到这个问题Creating a repeating timer reminder in Java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多