CronJob控制器

  CronJob控制器用于管理Job控制器资源的运行时间。Job控制器定义的作业任务在其控制器资源创建后便会立即进行,但是CronJob可类似于Linux操作系统的周期性任务作业计划(crontab)的方式控制其运行的时间点及重复运行的方式,具体如下:

  在未来某时间点运行作业一次

  在指定的时间点重复运行作业一次

  CronJob对象支持使用的时间格式类似于Crontab,略有不同的是,CronJob控制器在指定的时间点时,“?”和“*”的意义相同,都表示任何可用的有效值。

1. CronJob资源清单说明

  查看定义CronJob资源需要的字段有哪些

[root@k8s-master1 ~]# kubectl explain cronjob
KIND:     CronJob
VERSION:  batch/v1beta1

DESCRIPTION:
     CronJob represents the configuration of a single cron job.

FIELDS:
   apiVersion   <string> #api版本
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string> #资源类型
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata     <Object>  #元数据
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>  #定义容器的
     Specification of the desired behavior of a cron job, including the
     schedule. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status       <Object> #状态,不可更改
     Current status of a cron job. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

  查看CronJob控制器的spec字段可嵌套使用的以下字段:

[root@k8s-master1 ~]# kubectl explain cronjob.spec
KIND:     CronJob
VERSION:  batch/v1beta1

RESOURCE: spec <Object>

DESCRIPTION:
     Specification of the desired behavior of a cron job, including the
     schedule. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

     CronJobSpec describes how the job execution will look like and when it will
     actually run.

FIELDS:
   concurrencyPolicy    <string> #并发执行策略,可用值有"Allow","Forbid","Replace",用于定义前一次作业运行尚未完成时是否以及如何运行后一次的作业。
     Specifies how to treat concurrent executions of a Job. Valid values are: -
     "Allow" (default): allows CronJobs to run concurrently; - "Forbid": forbids
     concurrent runs, skipping next run if previous run hasn't finished yet; -
     "Replace": cancels currently running job and replaces it with a new one

   failedJobsHistoryLimit       <integer> #为失败的任务执行保留的历史记录数,默认为1
     The number of failed finished jobs to retain. This is a pointer to
     distinguish between explicit zero and not specified. Defaults to 1.

   jobTemplate  <Object> -required- #Job控制器模板,用于为CronJob控制器生成job对象;必选字段。
     Specifies the job that will be created when executing a CronJob.

   schedule     <string> -required-   #Cron格式的作业调度运行时间点;必须字段
     The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron.

   startingDeadlineSeconds      <integer>  #因各种原因缺乏执行作业的时间点所导致的启动作业错误的超时时长,会被计入错误历史记录
     Optional deadline in seconds for starting the job if it misses scheduled
     time for any reason. Missed jobs executions will be counted as failed ones.

   successfulJobsHistoryLimit   <integer> #为成功的任务执行保留的历史记录数,默认为3
     The number of successful finished jobs to retain. This is a pointer to
     distinguish between explicit zero and not specified. Defaults to 3.

   suspend      <boolean>  #是否挂起后续任务执行,默认为false,对运行中的作业不会产生影响。
     This flag tells the controller to suspend subsequent executions, it does
     not apply to already started executions. Defaults to false.

2. 创建CronJob对象

  下面是一个定义在资源清单文件中的cronjob资源对象示例,它每隔1分钟运行一次由jobTemplate定义的简单任务:

[root@k8s-master1 ~]# mkdir cronjob
[root@k8s-master1 ~]# cd cronjob/
[root@k8s-master1 cronjob]# vim cronjob-demo.yaml
You have new mail in /var/spool/mail/root
[root@k8s-master1 cronjob]# cat cronjob-demo.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cronjob-demo
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          containers:
          - name: hello
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            args:
            - "bin/sh"
            - "-c"
            - "for i in 9 8 7 6 5 4 3 2 1; do echo $i; done"

  运行资源创建命令创建上述CronJob资源对象,而后通过资源对象的相关信息了解运行状态。

[root@k8s-master1 cronjob]# kubectl apply -f cronjob-demo.yaml
cronjob.batch/cronjob-demo created
You have new mail in /var/spool/mail/root
[root@k8s-master1 cronjob]# kubectl get cronjobs
NAME           SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob-demo   */1 * * * *   False     0        <none>          10s

  查看创建的资源状态:

[root@k8s-master1 cronjob]# kubectl get cronjobs
NAME           SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob-demo   */1 * * * *   False     0        45s             90s
You have new mail in /var/spool/mail/root
[root@k8s-master1 cronjob]# kubectl get jobs
NAME                      COMPLETIONS   DURATION   AGE
cronjob-demo-1662909060   1/1           19s        49s
[root@k8s-master1 cronjob]# kubectl get pods -o wide
NAME                            READY   STATUS      RESTARTS   AGE   IP             NODE        NOMINATED NODE   READINESS GATES
cronjob-demo-1662909060-c9qhv   0/1     Completed   0          55s   10.244.36.87   k8s-node1   <none>           <none>

  一旦不再需要 Cron Job,简单地可以使用 kubectl 命令删除它

[root@k8s-master1 cronjob]# kubectl delete cronjobs cronjob-demo
cronjob.batch "cronjob-demo" deleted
[root@k8s-master1 cronjob]# kubectl get cronjobs
No resources found in default namespace.
You have new mail in /var/spool/mail/root
[root@k8s-master1 cronjob]# kubectl get jobs
No resources found in default namespace.

3. CronJob的控制机制

  CronJob控制器是一个更高级别的资源,它以Job控制器资源为管控对象,并借助它管理pod资源对象。因此,要使用类似如下命令查看某CronJob控制器创建的Job资源对象。可列出的Job对象数量取决于CronJob资源的cronjob.spec.successfulJobsHistoryLimit的属性值,默认为3

[root@k8s-master1 cronjob]# kubectl get cronjobs
NAME           SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob-demo   */1 * * * *   False     0        57s             4m42s
[root@k8s-master1 cronjob]# kubectl get jobs
NAME                      COMPLETIONS   DURATION   AGE
cronjob-demo-1662909120   1/1           7s         2m58s
cronjob-demo-1662909180   1/1           3s         117s
cronjob-demo-1662909240   1/1           4s         57s
[root@k8s-master1 cronjob]# kubectl get pods -o wide
NAME                            READY   STATUS      RESTARTS   AGE    IP             NODE        NOMINATED NODE   READINESS GATES
cronjob-demo-1662909120-l8h5s   0/1     Completed   0          3m2s   10.244.36.89   k8s-node1   <none>           <none>
cronjob-demo-1662909180-c2czr   0/1     Completed   0          2m1s   10.244.36.92   k8s-node1   <none>           <none>
cronjob-demo-1662909240-d24lv   0/1     Completed   0          61s    10.244.36.93   k8s-node1   <none>           <none>

  如果作业重复执行时指定时间点接近,而作业执行时长(普遍或偶尔)跨过了其两次执行的时间长度,则会出现两个pod对象同时存在的情形。有些Job对象可能会存在无法或不能同时运行的情况,这个时候就要通过cronjob.spec.concurrencyPolicy属性值控制作业并存的机制,其默认“Allow”,即允许前后job,甚至属于同一个CronJob的更多job同时运行。其他两个可用值中,“Forbid”用于禁止前后两个job同时运行,如果前一个尚未结束,后一个不予启动,“Replace”用于让后一个job取代前一个,即终止前一个并启动后一个。

   

posted @ 2022-09-11 23:32  出水芙蓉·薇薇  阅读(51)  评论(0编辑  收藏  举报