一、Job和CronJob是什么?

Job:一次性任务
CronJob:定时任务

二、Job和CronJob可以做什么?

我们的应用系统经常需要一些离线作业,比如数据统计分析、数据备份等功能需求,kubernetes为我们提供了Job和CronJob两种资源对象来应对这种需求。

其中Job负责一次性任务,也就是仅执行一次的任务,它保证批处理任务的一个或者多个Pod成功结束,而CronJob在Job的基础上增加了时间调度,比如每隔1小时执行一次等周期性的任务。

三、简单使用

1、Job

(1)定义一个Job

apiVersion: batch/v1
kind: Job
metadata:
  name: job-print-date
spec:
  template:
    spec:
      containers:
      - name: container-busybox
        image: busybox:1.28
        imagePullPolicy: IfNotPresent
        command:
        - "sh"
        - "-c"
        - "date"
      restartPolicy: Never
  backoffLimit: 4

说明:
1)上面Job创建一个busybox容器,容器启动后执行date命令。
2)重启策略restartPolicy:
(1)Never:容器启动失败时,会创建新的容器
(2)OnFailure:容器启动失败时,重新启动该容器,不会创建新的容器。
3)通过kubectl apply -f命令创建Job

(2)查看Job

通过kubectl get jobs查看Job

[root@test-99 jobs]# kubectl get job
NAME             COMPLETIONS   DURATION   AGE
job-print-date   1/1           2s         5s
[root@test-99 jobs]# 
[root@test-99 jobs]# kubectl get pods
NAME                   READY   STATUS      RESTARTS   AGE
busybox                1/1     Running     76         3d5h
job-print-date-v4dqd   0/1     Completed   0          15s
pod-pvc-busybox        1/1     Running     23         23h
volume-configmap       1/1     Running     60         2d12h
volume-emptydir        2/2     Running     142        2d23h
volume-hostpath        1/1     Running     71         2d23h
[root@test-99 jobs]# kubectl logs job-print-date-v4dqd
Thu Dec 29 13:59:14 UTC 2022

从上面的信息可以得知job-print-date Job创建成功,且通过该Job创建的Pod job-print-date-v4dqd 也创建成功,通过kubectl logs命令查看Pod 日志,可以看到日期信息正常输出。

(3)删除Job

Job执行成功之后,并不会自动删除,需要人工清理,可以通过kubectl delete -f命令来删除,删除Job时,该Job创建的Pod也会一并被删除。

[root@test-99 jobs]# kubectl delete -f 01-create-job.yml 
job.batch "job-print-date" deleted
[root@test-99 jobs]# kubectl get jobs
No resources found in default namespace.
[root@test-99 jobs]# kubectl get pods
NAME               READY   STATUS    RESTARTS   AGE
busybox            1/1     Running   77         3d5h
pod-pvc-busybox    1/1     Running   23         23h
volume-configmap   1/1     Running   60         2d12h
volume-emptydir    2/2     Running   144        3d
volume-hostpath    1/1     Running   71         2d23h
[root@test-99 jobs]# 

2、CronJob

(1)定义一个CronJob

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cronjob-print-date
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: container-busybox
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure

CronJob就是在Job的基础上加入cron表达式,如上面配置的schedule,* * * * * 就是一个cron表达式,表示每分钟执行一次。

cron表达式的语法如下:

# ┌───────────── 分钟 (0 - 59)
# │ ┌───────────── 小时 (0 - 23)
# │ │ ┌───────────── 月的某天 (1 - 31)
# │ │ │ ┌───────────── 月份 (1 - 12)
# │ │ │ │ ┌───────────── 周的某天 (0 - 6)(周日到周一;在某些系统上,7 也是星期日)
# │ │ │ │ │                          或者是 sun,mon,tue,web,thu,fri,sat
# │ │ │ │ │
# │ │ │ │ │
# * * * * *

(2)查看CronJob

通过kubectl get cj 命令查看CronJob

[root@test-99 jobs]# kubectl get cj
NAME                 SCHEDULE    SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cronjob-print-date   * * * * *   False     0        24s             6m7s
[root@test-99 jobs]# kubectl get pods
NAME                                READY   STATUS      RESTARTS   AGE
busybox                             1/1     Running     77         3d5h
cronjob-print-date-27872065-hp48p   0/1     Completed   0          2m18s
cronjob-print-date-27872066-x7rcr   0/1     Completed   0          78s
cronjob-print-date-27872067-xrmff   0/1     Completed   0          18s
pod-pvc-busybox                     1/1     Running     23         23h
volume-configmap                    1/1     Running     60         2d12h
volume-emptydir                     2/2     Running     144        3d
volume-hostpath                     1/1     Running     71         2d23h
[root@test-99 jobs]# kubectl logs cronjob-print-date-27872067-xrmff
Thu Dec 29 14:27:00 UTC 2022
Hello from the Kubernetes cluster
[root@test-99 jobs]# kubectl logs cronjob-print-date-27872066-x7rcr
Thu Dec 29 14:26:00 UTC 2022
Hello from the Kubernetes cluster
[root@test-99 jobs]# kubectl logs cronjob-print-date-27872065-hp48p
Thu Dec 29 14:25:00 UTC 2022
Hello from the Kubernetes cluster
[root@test-99 jobs]# 

通过CronJob创建的Pod,可以通过kubectl get pods命令查看,并通过kubectl logs查看每个Pod打印的日期,可以发现,每隔一分钟执行一次。

通过kubectl get cj -o yaml 查看详细配置信息

[root@test-99 jobs]# kubectl get cj cronjob-print-date -o yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"batch/v1","kind":"CronJob","metadata":{"annotations":{},"name":"cronjob-print-date","namespace":"default"},"spec":{"jobTemplate":{"spec":{"template":{"spec":{"containers":[{"command":["/bin/sh","-c","date; echo Hello from the Kubernetes cluster"],"image":"busybox:1.28","imagePullPolicy":"IfNotPresent","name":"hello"}],"restartPolicy":"OnFailure"}}}},"schedule":"* * * * *"}}
  creationTimestamp: "2022-12-29T14:42:20Z"
  name: cronjob-print-date
  namespace: default
  resourceVersion: "422404"
  uid: 699bd2c3-0b88-43d3-af4d-e43eefb9a552
spec:
  concurrencyPolicy: Allow
  failedJobsHistoryLimit: 1
  jobTemplate:
    metadata:
      creationTimestamp: null
    spec:
      template:
        metadata:
          creationTimestamp: null
        spec:
          containers:
          - command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            name: hello
            resources: {}
            terminationMessagePath: /dev/termination-log
            terminationMessagePolicy: File
          dnsPolicy: ClusterFirst
          restartPolicy: OnFailure
          schedulerName: default-scheduler
          securityContext: {}
          terminationGracePeriodSeconds: 30
  schedule: '* * * * *'
  successfulJobsHistoryLimit: 3
  suspend: false
status: {}

其中successfulJobsHistoryLimit:3 表示只保留3个成功的Job,我们可以通过kubectl get jobs查看,而failedJobsHistoryLimit: 1表示只保留1个失败的Job。

[root@test-99 jobs]# kubectl get job 
NAME                          COMPLETIONS   DURATION   AGE
cronjob-print-date-27872084   1/1           1s         2m48s
cronjob-print-date-27872085   1/1           1s         108s
cronjob-print-date-27872086   1/1           1s         48s

(3)删除CronJob

可以通过kubectl delete cj或者kubectl delete -f命令删除CronJob。

[root@test-99 jobs]# kubectl delete cj cronjob-print-date
cronjob.batch "cronjob-print-date" deleted
打赏
支付宝 微信
上一篇 下一篇