如何运行计时器?

sar*_*rah 3 java

我想运行一个计时器,说30秒后时间到期,怎么办呢?有些任务只运行几秒钟然后显示已过期,我该怎么办?

Ada*_*ski 7

我推荐使用ScheduledExecutorService来自java.util.concurrent包,里面有比其他更丰富的API Timer在JDK中实现.

// Create timer service with a single thread.
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();

// Schedule a one-off task to run in 10 seconds time.
// It is also possible to schedule a repeating task.
timer.schedule(new Callable<Void>() {
  public Void call() {
    System.err.println("Expired!");

    // Return a value here.  If we know we don't require a return value
    // we could submit a Runnable instead of a Callable to the service.
    return null;
  }
}, 10L, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)