0

我有一个 ScheduledExecutorService,我想用它来安排具有一定延迟的 Runnable 的执行。但是,当我调用它的 schedule 方法时,延迟会被完全忽略,Runnable 会立即执行。这是我的代码:

我的 ScheduledExecutorService 构造函数:

    private static ScheduledExecutorService existQueuePool = Executors.newScheduledThreadPool(1);

这是对其 schedule 方法的调用(由 Logs 包围):

Log.d(TAG,"Before schedule");
ScheduledFuture<?> mScheduledFuture = existQueuePool.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG,"Setting clearMessageTask for exist messages in the existQueuePool.");                       
                        clearMessageTask(mContext.getString(R.string.existType));
                    }
                }, 1000L, TimeUnit.MILLISECONDS);
Log.d(TAG,"After schedule");

日志让我看到“在计划之前”和“设置清除...”之间只有 20-30 毫秒的延迟,而不是我预期的 1000 毫秒。

schedule 方法的文档如下:

创建并执行在给定延迟后启用的一次性操作。

在这种情况下,“启用”一词的确切含义是什么?

任何帮助将不胜感激。

编辑:即使使用 Long (1000L),代码似乎也会立即执行。

4

1 回答 1

1

我认为你说得对。尝试1000L,作为long预期的值,而不是int.

编辑:我自己试过了,你的代码对我有用:

package testdelay;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class TestDelay {

    private static final ScheduledExecutorService existQueuePool = Executors.newScheduledThreadPool(1);
    private static long start;
    private static long end;
    public static void main(String[] args) {
        start = System.currentTimeMillis();
        System.out.println("Before execution: " + start);
        ScheduledFuture<?> mScheduledFuture = existQueuePool.schedule(new Runnable() {
                    @Override
                    public void run() {
                        end = System.currentTimeMillis();
                        System.out.println("Executed at: " + end);
                        System.out.println("Executed after delay of : " + (end - start) + " ms.");
                    }
                }, 1000L, TimeUnit.MILLISECONDS);
    }
}

输出:

Before execution: 1386350613147
Executed at: 1386350614149
Executed after delay of : 1002 ms.

它似乎是即时运行的,因为您在可运行文件之外记录了一条消息,该消息在提交到服务后立即执行。您应该将它记录在可运行文件本身中以查看它何时运行。

于 2013-12-04T17:58:30.923 回答