k8s的CronJob

一、CronJob介绍

	可以利用 CronJobs 执行基于时间调度的任务。这些自动化任务和 Linux 或者 Unix 系统的 Cron 任务类似
	CronJobs在创建周期性以及重复性的任务时很有帮助,例如执行备份操作或者发送邮件。CronJobs 也可以在特定时间调度单个任务,例如你想调度低活跃周期的任务。

二、创建一个Job

2.1、yaml文件创建

[root@k8s-master01 app]# cat  cronjob.yaml 
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            args:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure

# 创建job
kubectl create -f cronjob.yaml 

2.2、查看job

[root@k8s-master01 app]# kubectl get jobs --watch
NAME               COMPLETIONS   DURATION   AGE
hello-1609167960   0/1           7m44s      7m44s
hello-1609168020   0/1           6m42s      6m42s
hello-1609168080   0/1           5m41s      5m41s
hello-1609168140   0/1           4m50s      4m50s
hello-1609168200   0/1           3m49s      3m49s
hello-1609168260   1/1           21s        2m48s
hello-1609168320   1/1           2s         107s
hello-1609168380   1/1           3s         46s

[root@k8s-master01 app]# kubectl get cronjob hello
NAME    SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
hello   */1 * * * *   False     6        4s              8m20s

# 删除
[root@k8s-master01 app]# kubectl delete cronjob hello
cronjob.batch "hello" deleted

2.3、yaml文件参数介绍

kubectl get cj hello -oyaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  labels:
    run: hello
  name: hello
  namespace: default
spec:
  concurrencyPolicy: Allow #并发调度策略:Allow运行同时运行过个任务。
								# Forbid:不运行并发执行。
								# Replace:替换之前的任务
  failedJobsHistoryLimit: 1 # 保留失败的任务数。
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      template:
        metadata:
          creationTimestamp: null
          labels:
            run: hello
        spec:
          containers:
          - args:
            - /bin/sh
            - -c
            - date
            image: nginx
            imagePullPolicy: IfNotPresent
            name: hello
            resources: {}
            terminationMessagePath: /dev/termination-log
            terminationMessagePolicy: File
          dnsPolicy: ClusterFirst
          restartPolicy: OnFailure
          schedulerName: default-scheduler
          securityContext: {}
          terminationGracePeriodSeconds: 30
  schedule: '*/1 * * * *'  #调度的策略 分时日月周
  successfulJobsHistoryLimit: 3 # 成功的Job保留的次数
  suspend: false # 挂起,true:cronjob不会被执行。
status: {}
原文地址:https://www.cnblogs.com/hsyw/p/14201841.html