运行任务

您可以通过在 Kf 中以任务形式运行短期工作流来执行这些工作流。任务在应用下运行,这意味着每个任务都必须有一个关联的应用。每个任务执行过程都会使用父应用中的构建工件。由于任务是短期的,因此应用不会部署为长时间运行的应用,不应为应用或任务创建路由。

推送用于运行任务的应用

  1. 克隆 test-app 代码库

    git clone https://github.com/cloudfoundry-samples/test-app test-app
    cd test-app
    
  2. 推送应用。

    使用 kf push APP_NAME --task 命令推送应用。--task 标志表示应用的用途用于运行任务,因此不会在应用上创建路由,也不会部署为长时间运行的应用。

    kf push test-app --task
    
  3. 通过列出应用,确认没有创建应用实例或路由。

    kf apps
    

    请注意,该应用尚未启动,也没有网址。

    Listing Apps in Space: test-space
    Name                     Instances  Memory  Disk  CPU   URLs
    test-app                 stopped    1Gi     1Gi   100m  <nil>
    

在应用上运行任务

当您在应用上运行任务时,可以使用 --command 标志选择性指定启动命令。如果未指定启动命令,则使用应用中指定的启动命令。如果应用未指定启动命令,它会查找容器映像的 CMD 配置。必须存在启动命令才能成功运行任务。

kf run-task test-app --command "printenv"

您将看到如下内容,确认您的任务已提交。

Task test-app-gd8dv is submitted successfully for execution.

系统会自动生成任务名称,该名称以应用名称为前缀,并以任意字符串为后缀。任务名称是同一集群中 Tasks 的唯一标识符。

指定任务资源限制

资源限制(例如 CPU 核心/内存限制/磁盘配额)可以在应用中(在 kf push 期间)或 kf run-task 命令期间指定。kf run-task 命令中指定的限制优先于应用中指定的限制。

如需在应用中指定资源限制,您可以在 kf push 命令中使用 --cpu-cores--memory-limit--disk-quota 标志。

kf push test-app --command "printenv" --cpu-cores=0.5 --memory-limit=2G --disk-quota=5G --task

如需在应用中替换这些限制,您可以在 kf run-task 命令中使用 --cpu-cores--memory-limit--disk-quota 标志。

kf run-task test-app --command "printenv" --cpu-cores=0.5 --memory-limit=2G --disk-quota=5G

为任务指定自定义显示名

您可以选择性地使用 --name 标志为任务指定自定义显示名,以方便识别/分组。

$ kf run-task test-app --command "printenv" --name foo
Task test-app-6swct is submitted successfully for execution.

$ kf tasks test-app
Listing Tasks in Space: test space
Name              ID  DisplayName        Age    Duration  Succeeded  Reason
test-app-6swct    3   foo                1m     21s       True       <nil>

管理任务

使用 kf tasks APP_NAME 命令查看应用的所有任务。

$ kf tasks test-app
Listing Tasks in Space: test space
Name              ID  DisplayName        Age    Duration  Succeeded  Reason
test-app-gd8dv    1   test-app-gd8dv     1m     21s       True       <nil>

取消任务

使用 kf terminate-task 命令取消活跃任务。

按任务名称取消任务。

$ kf terminate-task test-app-6w6mz
Task "test-app-6w6mz" is successfully submitted for termination

或按 APP_NAME + 任务 ID 取消任务。

$ kf terminate-task test-app 2
Task "test-app-6w6mz" is successfully submitted for termination

已取消的任务的状态为 PipelineRunCancelled

$ kf tasks test-app
Listing Tasks in Space: test space
Name              ID  DisplayName        Age    Duration  Succeeded  Reason
test-app-gd8dv    1   test-app-gd8dv     1m     21s       True       <nil>
test-app-6w6mz    2   test-app-6w6mz     38s    11s       False      PipelineRunCancelled

查看任务日志

使用 kf logs APP_NAME --task 命令查看任务的日志。

$ kf logs test-app --task