在配置的时间后以编程方式从订阅中终止 PubSubIO.readMessages?

Programmatically terminating PubSubIO.readMessages from Subscription after configured time?

我希望从 PubSub 主题的订阅中安排具有 PubSubIO.readString 的数据流。我怎样才能让工作在配置的时间间隔后终止?我的用例不是让作业 运行 持续一整天,因此希望安排开始,然后在作业中配置的时间间隔后停止。

Pipeline
    .apply(PubsubIO.readMessages().fromSubscription("some-subscription"))

来自docs

If you need to stop a running Cloud Dataflow job, you can do so by issuing a command using either the Cloud Dataflow Monitoring Interface or the Cloud Dataflow Command-line Interface.

我假设您对通过控制台手动停止作业不感兴趣,这让您只能使用命令行解决方案。如果您打算将数据流作业安排到 运行,例如每天,那么你就知道你希望它在什么时候停止(启动时间 + "configured interval")。在这种情况下,您可以将 cron 作业配置为每天 运行 gcloud dataflow jobs cancel 的那个时间。例如,以下脚本将取消当天启动的所有活动作业:

#!/bin/bash
gcloud dataflow jobs list --status=active --created-after=-1d \
| awk '{print ;}' | tail -n +2 \
| while read -r JOB_ID; do gcloud dataflow jobs cancel $JOB_ID; done

另一种解决方案是使用 Runtime.getRuntime.exec(). You can schedule this to run after a specific interval using java.util.Timer().schedule() as noted here 在 java 代码中调用 gcloud 命令。这样您就可以确保您的作业在提供的时间间隔后停止,无论您何时启动它。

更新

@RoshanFernando 在评论中正确指出实际上有一个 SDK method 可以取消管道。