【问题标题】:Why is my scheduleAtFixedRate delay ignored?为什么我的 scheduleAtFixedRate 延迟被忽略?
【发布时间】:2017-01-15 15:24:46
【问题描述】:

我想每 4 秒执行一次函数,第一组代码工作得非常好,每 4 秒打印一次“测试”。

ScheduledExecutorService SES = Executors.newSingleThreadScheduledExecutor();
            SES.scheduleAtFixedRate(new UpdateGraph(), 4, 4, TimeUnit.SECONDS);

public class UpdateGraph implements Runnable {
    @Override
    public void run() {
        Log.v("testing", "testing");
    }
}

但是,如果我在 runnable 中有一个 for 循环,则“测试”不再像我要求的那样延迟。

public class UpdateGraph implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < numberOfFiles; i++) {
            final double t = i;
            final int y = i;
            lineGraphPosture.addNewPoints(PointPosture.singlePoint(t, getNextX().get(y)));
            graphView.repaint();
            Log.v("testing", "testing");
        }
    }
}

我知道问题出在 for 循环上,但不知道为什么?

请高人指点一下 =)

【问题讨论】:

  • 你正在运行一个循环。当然,所有 numberOfFiles 都会快速连续打印出来。它们正在发生,它们之间没有任何延迟。
  • 您认为在 numberOfFiles 的元素之间引入 daly 的正确方法是什么?
  • Thread.sleep?

标签: java android runnable scheduledexecutorservice


【解决方案1】:

如果你希望你的 Runnable 只被执行 numberOfFiles 次,那么在这里调度执行器是错误的选择。而是使用 SingleThreadExecutor 并执行以下操作:

ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < numberOfFiles; i++) {
    executor.submit(runnable);
    try {
        executor.awaitTermination(4L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

【讨论】:

    【解决方案2】:

    使用SchedulorExecutorService 时必须小心未捕获的异常。如果您的 UpdateGraph 在运行时抛出异常,则不会再安排执行。

    我建议您将此块包装在 try/catch 中并记录最终异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 2013-09-30
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多