Scala Future执行完成后如何终止Databricks Notebook运行
问题分析
- 你当前代码提交的3个
Future是异步非阻塞的,主逻辑不会等待所有Future执行完成就会直接走到println("finished futures - yay! :)")以及后续的Thread.sleep逻辑,所以才会出现任务没跑完就走到最后、必须等5小时才结束的问题 - 直接在Future块后面调用
dbutils.notebook.exit()是不可行的,因为调用的时候Future还没执行完,会直接终止整个notebook,任务会直接中断
可行的解决方案
你可以将所有提交的Future存入列表,通过Future.sequence合并为一个总Future,再用Await.result等待所有任务执行完成,完成后直接调用退出方法即可,修改后的代码如下:
import scala.concurrent.{Future, blocking, Await} import java.util.concurrent.Executors import scala.concurrent.ExecutionContext import com.databricks.WorkflowException import scala.concurrent.duration._ // 导入时间单位工具 val numNotebooksInParallel = 15 // If you create too many notebooks in parallel the driver may crash when you submit all of the jobs at once. // This code limits the number of parallel notebooks. implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(numNotebooksInParallel)) val ctx = dbutils.notebook.getContext() // The simplest interface we can have but doesn't // have protection for submitting to many notebooks in parallel at once println("starting parallel jobs... hang tight") // 把所有Future存入列表统一管理 val allFutures = List( Future { process("pro","bseg") process("prc","bkpf") process("prc","bseg") process("pr4","bkpf") process("pr4","bseg") println("done with future1") }, Future { process("pr5","bkpf") process("pr5","bseg") process("pri","bkpf") process("pri","bseg") process("pr9","bkpf") println("done with future2") }, Future { process("pr9","bseg") process("prl","bkpf") process("prl","bseg") process("pro","bkpf") println("done with future3") } ) // 合并所有Future,等待所有任务完成,最多等待5小时 Await.result(Future.sequence(allFutures), 5.hours) println("all futures finished successfully!") // 所有任务完成后直接退出notebook dbutils.notebook.exit("SUCCESS")
要点说明
Future.sequence会将List[Future]转换为Future[List],只有列表里所有Future都成功执行完成,这个合并后的Future才会进入完成状态Await.result会阻塞当前主线程,直到合并后的Future完成,或者达到你设置的超时时间,超时会直接抛出异常终止任务,避免无限等待- 所有任务完成后会立刻执行后续的
dbutils.notebook.exit(),不需要再等待剩余的sleep时间,也不会出现主逻辑走完无输出的问题 - 如果需要处理任务失败的情况,可以在
Await.result外层加try-catch捕获异常,做对应的失败处理后再退出notebook
内容的提问来源于stack exchange,提问作者steven hurwitt
相关产品推荐
相关产品推荐

