2017-04-26 80 views
2

如何使用Java并发API获取对计划执行的任务的引用?获取对计划任务的引用

我可以做这样的事情,并保持参考myRunnable:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 
SimpleRunnable myRunnable = new SimpleRunnable(); 
exec.scheduleAtFixedRate(myRunnable, 0, 2, TimeUnit.SECONDS); 

但有使用执行人服务或ScheduledFuture获得参考的方法吗?

This question显示Future对象的集合,并讨论它们保留对任务的引用,但我没有看到公开的API方法公开它。

回答

0

未来引用表示异步任务的计算结果,而任务本身基本上是您传递给scheduleAtFixedRate方法(以下示例中的'myRunnable')的可运行引用。

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); 
SimpleRunnable myRunnable = new SimpleRunnable(); 
ScheduledFuture<?> future = exec.scheduleAtFixedRate(myRunnable, 0, 2, 
TimeUnit.SECONDS); 

我不认为你有办法从执行程序本身了Runnable。 请详细说明你愿意做什么,我会尽力协助你。

+0

是的,我可以挂在ScheduledFuture对象的引用上,但我仍然没有看到任何获取任务引用的方法。 – sjgp

+0

我不认为你有办法从执行程序本身检索Runnable。请详细说明你愿意做什么,我会尽力协助你。 –

+0

我正在探索设计选项,要求定期运行任务以执行一些工作,并收集信息。第二个独立流程需要访问该信息。访问不需要通过Executor或Future API,我可以设计另一种解决方案,因为引用任务的方式似乎不是一种选择。谢谢你的想法! – sjgp