简体   繁体   English

如何返回传递给 ScheduledExecutorService.schedule 的 Runnable 或 Callable 的返回值

[英]How to return the return value of the Runnable or Callable passed to ScheduledExecutorService.schedule

public Record task(Id id, Supplier<Record> elector) {
    // elector is: '() -> functionName(id, stats)'

    final long delayTime = calculateTimeToDelay();

    ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

    // Cannot resolve method 'schedule(Record, long, TimeUnit)'
    return ses.schedule(elector.get(), timeToDelay, TimeUnit.MILLISECONDS);

    // try {
    //     Thread.sleep(delayTime);
    // } catch (final InterruptedException e) {
    //     log.error(e);
    // }
    // return elector.get();
}

As you can see, the commented out code returns what elector.get() returns, which is a Record.如您所见,注释掉的代码返回了elector.get() 返回的内容,即Record。 But instead of using Thread.sleep(delayTime), I'm trying to use ScheduledExecutorService to call elector.get() after a few milliseconds of a delay.但是,我没有使用 Thread.sleep(delayTime),而是尝试使用 ScheduledExecutorService 在几毫秒的延迟后调用lector.get()。 Not sure what Runnable and Callable is and whether elector.get() would count as one of those.不确定 Runnable 和 Callable 是什么,以及选举者.get() 是否会算作其中之一。

Some direction here would be appreciated.这里的一些方向将不胜感激。

ScheduledExecutorService.schedule需要Callable ,因此您必须将Supplier转换为Callable ,例如,通过方法参考语法:

ses.schedule(elector::get, timeToDelay, TimeUnit.MILLISECONDS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM