Tasks
Setup an extension API server
Administer a Cluster
Access Clusters Using the Kubernetes API (EN)
Access Services Running on Clusters (EN)
Advertise Extended Resources for a Node (EN)
Autoscale the DNS Service in a Cluster (EN)
Change the Reclaim Policy of a PersistentVolume (EN)
Change the default StorageClass (EN)
Cluster Management (EN)
Configure Multiple Schedulers (EN)
Configure Out Of Resource Handling (EN)
Configure Quotas for API Objects (EN)
Control CPU Management Policies on the Node (EN)
Control Topology Management Policies on a node (EN)
Customizing DNS Service (EN)
Debugging DNS Resolution (EN)
Declare Network Policy (EN)
Developing Cloud Controller Manager (EN)
Enabling Endpoint Slices (EN)
Encrypting Secret Data at Rest (EN)
Guaranteed Scheduling For Critical Add-On Pods (EN)
IP Masquerade Agent User Guide (EN)
Kubernetes Cloud Controller Manager (EN)
Limit Storage Consumption (EN)
Namespaces Walkthrough (EN)
Operating etcd clusters for Kubernetes (EN)
Reconfigure a Node's Kubelet in a Live Cluster (EN)
Reserve Compute Resources for System Daemons (EN)
Safely Drain a Node while Respecting the PodDisruptionBudget (EN)
Securing a Cluster (EN)
Set Kubelet parameters via a config file (EN)
Set up High-Availability Kubernetes Masters (EN)
Share a Cluster with Namespaces (EN)
Using CoreDNS for Service Discovery (EN)
Using NodeLocal DNSCache in Kubernetes clusters (EN)
Using a KMS provider for data encryption (EN)
Using sysctls in a Kubernetes Cluster (EN)
Accessing Clusters
Use Port Forwarding to Access Applications in a Cluster
Provide Load-Balanced Access to an Application in a Cluster
Use a Service to Access an Application in a Cluster
删除 StatefulSet
Create an External Load Balancer
配置你的云平台防火墙
List All Container Images Running in a Cluster
Configure DNS for a Cluster
Federation - Run an App on Multiple Clusters
Administer-clusters
Access Clusters Using the Kubernetes API (EN)
Advertise Extended Resources for a Node (EN)
Autoscale the DNS Service in a Cluster (EN)
Configure Multiple Schedulers (EN)
Configure Out Of Resource Handling (EN)
Configure Quotas for API Objects (EN)
Control Topology Management Policies on a node (EN)
Debugging DNS Resolution (EN)
Developing Cloud Controller Manager (EN)
Enabling Endpoint Slices (EN)
Encrypting Secret Data at Rest
IP Masquerade Agent User Guide (EN)
Kubernetes Cloud Controller Manager (EN)
Limit Storage Consumption (EN)
Namespaces Walkthrough (EN)
Operating etcd clusters for Kubernetes (EN)
Reconfigure a Node's Kubelet in a Live Cluster (EN)
Reserve Compute Resources for System Daemons (EN)
Safely Drain a Node while Respecting the PodDisruptionBudget (EN)
Securing a Cluster (EN)
Set up High-Availability Kubernetes Masters (EN)
Share a Cluster with Namespaces (EN)
Using CoreDNS for Service Discovery (EN)
Using NodeLocal DNSCache in Kubernetes clusters (EN)
Using a KMS provider for data encryption (EN)
使用 Calico 来提供 NetworkPolicy
使用 Romana 来提供 NetworkPolicy
使用 Weave 网络来提供 NetworkPolicy
关键插件 Pod 的调度保证
在 Kubernetes 中配置私有 DNS 和上游域名服务器
在 Kubernetes 集群中使用 sysctl
声明网络策略
将 kubeadm 集群在 v1.8 版本到 v1.9 版本之间升级/降级
应用资源配额和限额
控制节点上的CPU管理策略
改变默认 StorageClass
更改 PersistentVolume 的回收策略
设置 Pod CPU 和内存限制
访问集群上运行的服务
通过配置文件设置 Kubelet 参数
配置命名空间下pod总数
集群管理
静态Pods
Extend kubectl with plugins (EN)
使用 Service 把前端连接到后端
使用Deployment运行一个无状态应用
同 Pod 内的容器使用共享卷通信
基于Replication Controller执行滚动升级
对 DaemonSet 执行回滚
弹缩StatefulSet
管理巨页(HugePages)
证书轮换
调度 GPU
运行一个单实例有状态应用
配置对多集群的访问

Edit This Page

Running Automated Tasks with a CronJob

你可以利用 CronJobs 执行基于时间调度的任务。这些自动化任务和 Linux 或者 Unix 系统的 Cron 任务类似。

CronJobs 在创建周期性以及重复性的任务时很有帮助,例如执行备份操作或者发送邮件。CronJobs 也可以在特定时间调度单个任务,例如你想调度低活跃周期的任务。

Note:

从集群版本1.8开始,batch/v2alpha1 API 组中的 CronJob 资源已经被废弃。 你应该切换到 API 服务器默认启用的 batch/v1beta1 API 组。本文中的所有示例使用了batch/v1beta1

CronJobs 有一些限制和特点。 例如,在特定状况下,同一个 CronJob 可以创建多个任务。 因此,任务应该是幂等的。 查看更多限制,请参考 CronJobs

准备开始

To check the version, enter kubectl version.

创建 CronJob

CronJob 需要一个配置文件。 本例中 CronJob 的.spec 配置文件每分钟打印出当前时间和一个问好信息:

application/job/cronjob.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure

想要运行示例的 CronJob,可以下载示例文件并执行命令:

$ kubectl create -f ./cronjob.yaml
cronjob "hello" created

或者你也可以使用 kubectl run 来创建一个 CronJob 而不需要编写完整的配置:

$ kubectl run hello --schedule="*/1 * * * *" --restart=OnFailure --image=busybox -- /bin/sh -c "date; echo Hello from the Kubernetes cluster"
cronjob "hello" created

创建好 CronJob 后,使用下面的命令来获取其状态:

$ kubectl get cronjob hello
NAME      SCHEDULE      SUSPEND   ACTIVE    LAST-SCHEDULE
hello     */1 * * * *   False     0         <none>

就像你从命令返回结果看到的那样,CronJob 还没有调度或执行任何任务。大约需要一分钟任务才能创建好。

$ kubectl get jobs --watch
NAME               DESIRED   SUCCESSFUL   AGE
hello-4111706356   1         1         2s

现在你已经看到了一个运行中的任务被 “hello” CronJob 调度。你可以停止监视这个任务,然后再次查看 CronJob 就能看到它调度任务:

$ kubectl get cronjob hello
NAME      SCHEDULE      SUSPEND   ACTIVE    LAST-SCHEDULE
hello     */1 * * * *   False     0         Mon, 29 Aug 2016 14:34:00 -0700

你应该能看到 “hello” CronJob 在 LAST-SCHEDULE 声明的时间点成功的调度了一次任务。有0个活跃的任务意味着任务执行完毕或者执行失败。

现在,找到最后一次调度任务创建的 Pod 并查看一个 Pod 的标准输出。请注意任务名称和 Pod 名称是不同的。

# Replace "hello-4111706356" with the job name in your system
$ pods=$(kubectl get pods --selector=job-name=hello-4111706356 --output=jsonpath={.items..metadata.name})

$ echo $pods
hello-4111706356-o9qcm

$ kubectl logs $pods
Mon Aug 29 21:34:09 UTC 2016
Hello from the Kubernetes cluster

删除 CronJob

当你不再需要 CronJob 时,可以用 kubectl delete cronjob 删掉它:

$ kubectl delete cronjob hello
cronjob "hello" deleted

删除 CronJob 会清除它创建的所有任务和 Pod,并阻止它创建额外的任务。你可以查阅 垃圾收集

编写 CronJob 声明信息

像 Kubernetes 的其他配置一样,CronJob 需要 apiVersionkind、 和 metadata 域。配置文件的一般信息,请参考 部署应用使用 kubectl 管理资源.

CronJob 配置也需要包括.spec.

Note:

对 CronJob 的所有改动,特别是它的 .spec,只会影响将来的运行实例。

时间安排

.spec.schedule.spec 需要的域。它使用了 Cron 格式串,例如 0 * * * * or @hourly ,做为它的任务被创建和执行的调度时间。

该格式也包含了扩展的 vixie cron 步长值。FreeBSD 手册中解释如下:

步长可被用于范围组合。范围后面带有 /<数字>'' 可以声明范围内的步幅数值。 例如,0-23/2” 可被用在小时域来声明命令在其他数值的小时数执行( V7 标准中对应的方法是0,2,4,6,8,10,12,14,16,18,20,22'')。 步长也可以放在通配符后面,因此如果你想表达每两小时”,就用 ``*/2” 。

Note:

调度中的问号 (?) 和星号 * 含义相同,表示给定域的任何可用值。

任务模版

.spec.jobTemplate是任务的模版,它是必须的。它和 Job的语法完全一样,除了它是嵌套的没有 apiVersionkind。 编写任务的 .spec ,请参考 编写任务的Spec

开始的最后期限

.spec.startingDeadlineSeconds 域是可选的。 它表示任务如果由于某种原因错过了调度时间,开始该任务的截止时间的秒数。过了截止时间,CronJob 就不会开始任务。 不满足这种最后期限的任务会被统计为失败任务。如果该域没有声明,那任务就没有最后期限。

CronJob 控制器会统计错过了多少次调度。如果错过了100次以上的调度,CronJob 就不再调度了。当没有设置 .spec.startingDeadlineSeconds 时,CronJob 控制器统计从status.lastScheduleTime到当前的调度错过次数。 例如一个 CronJob 期望每分钟执行一次,status.lastScheduleTime是 5:00am,但现在是 7:00am。那意味着120次调度被错过了,所以 CronJob 将不再被调度。 如果设置了 .spec.startingDeadlineSeconds 域(非空),CronJob 控制器统计从 .spec.startingDeadlineSeconds 到当前时间错过了多少次任务。 例如设置了 200,它会统计过去200秒内错过了多少次调度。在那种情况下,如果过去200秒内错过了超过100次的调度,CronJob 就不再调度。

并发性规则

.spec.concurrencyPolicy 也是可选的。它声明了 CronJob 创建的任务执行时发生重叠如何处理。spec 仅能声明下列规则中的一种:

请注意,并发性规则仅适用于相同 CronJob 创建的任务。如果有多个 CronJob,它们相应的任务总是允许并发执行的。

挂起

.spec.suspend域也是可选的。如果设置为 true ,后续发生的执行都会挂起。这个设置对已经开始的执行不起作用。默认是关闭的。

Caution:

在调度时间内挂起的执行都会被统计为错过的任务。当 .spec.suspendtrue 改为 false 时,且没有 开始的最后期限,错过的任务会被立即调度。

任务历史限制

.spec.successfulJobsHistoryLimit.spec.failedJobsHistoryLimit是可选的。 这两个域声明了有多少执行完成和失败的任务会被保留。 默认设置为3和1。限制设置为0代表相应类型的任务完成后不会保留。


reviewers: - chenopis

title: 使用 CronJob 运行自动化任务 content_template: templates/task

weight: 10

反馈