Kubernetes——CronJob控制器

CronJob控制器

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

  • 在未来某时间点运行作业一次。
  • 在指定的时间点重复运行作业。

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

一、创建 CronJob 对象

  CronJob 控制器的相关配置如下:

[root@mh-k8s-master-prd-243-24 ~]# kubectl explain cronjob
KIND:     CronJob
VERSION:  batch/v1beta1

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

FIELDS:
   apiVersion	<string>
     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

[root@mh-k8s-master-prd-243-24 ~]# 

  spec 字段常用嵌套如下:

 

[root@mh-k8s-master-prd-243-24 ~]# 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>
     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
	 并发执行策略,可用值有 "Allow"(允许)、"Forbid"(禁止)和 "Replace"(替换),
	 用于定义前一次作业运行尚未完成时是否以及如何运行后一次作业。

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

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

   schedule	<string> -required-
     The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron.
	 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>
     The number of successful finished jobs to retain. This is a pointer to
     distinguish between explicit zero and not specified. Defaults to 3.
	 为成功的任务执行保留的历史记录数,默认为 3.

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

[root@mh-k8s-master-prd-243-24 ~]#  

  下面是一个定义在资源清单文件(jaeger-es-index-cleaner.yaml)中的 CronJob 资源对象示例:

kind: CronJob
apiVersion: batch/v1beta1
metadata:
  name: jaeger-es-index-cleaner
  namespace: istio-system
  labels:
    app: jaeger
    app.kubernetes.io/component: cronjob-es-index-cleaner
    app.kubernetes.io/instance: jaeger
    app.kubernetes.io/managed-by: jaeger-operator
    app.kubernetes.io/name: jaeger-es-index-cleaner
    app.kubernetes.io/part-of: jaeger
  annotations:
    linkerd.io/inject: disabled
    prometheus.io/scrape: 'false'
    sidecar.istio.io/inject: 'false'
spec:
  schedule: 55 23 * * *
  concurrencyPolicy: Allow
  suspend: false
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      parallelism: 1
      template:
        metadata:
          creationTimestamp: null
          labels:
            app: jaeger
            app.kubernetes.io/component: cronjob-es-index-cleaner
            app.kubernetes.io/instance: jaeger
            app.kubernetes.io/managed-by: jaeger-operator
            app.kubernetes.io/name: jaeger-es-index-cleaner
            app.kubernetes.io/part-of: jaeger
          annotations:
            linkerd.io/inject: disabled
            prometheus.io/scrape: 'false'
            sidecar.istio.io/inject: 'false'
        spec:
          containers:
            - name: jaeger-es-index-cleaner
              image: >-
                registry.cn-beijing.aliyuncs.com/kubesphereio/jaeger-es-index-cleaner:1.17
              args:
                - '7'
                - >-
                  http://elasticsearch-logging-data.kubesphere-logging-system.svc:9200
              envFrom:
                - secretRef:
                    name: jaeger-secret
              env:
                - name: INDEX_PREFIX
                  value: logstash
              resources: {}
              terminationMessagePath: /dev/termination-log
              terminationMessagePolicy: File
              imagePullPolicy: IfNotPresent
          restartPolicy: Never
          terminationGracePeriodSeconds: 30
          dnsPolicy: ClusterFirst
          serviceAccountName: jaeger
          serviceAccount: jaeger
          securityContext: {}
          schedulerName: default-scheduler
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1

二、CronJob 的控制机制

  CronJob 控制器是一个更高级别的资源,它以 Job 控制器资源为其管控对象,并借助它管理 Pod 资源的对象。

  如果作业重复执行时指定的时间点较近,而作业执行时长跨过了其两次执行的时间长度,则会出现两个 Job 对象同时存在的情形。

  有些 Job 对象可能会存在无法或不能同时运行情形,这个时候就要通过 cronjob.spec.concruuencyPolicy 属性控制作业并存的机制,其默认值为

"Allow",即允许前后 Job,甚至属于同一个 CronJob 的更多 Job 同时运行。其他两个可用值中,

"Forbid" 用于禁止前后两个 Job 同时运行,如果前一个尚未结束,后一个则不予启动(跳过)。

"Replcae" 用于让后一个 Job 取代前一个,即终止前一个并启动后一个。

posted @ 2022-06-20 15:00  左扬  阅读(166)  评论(0编辑  收藏  举报
levels of contents