kubernetes cronjob job - ghdrako/doc_snipets GitHub Wiki

Clean job

...
spec:
  ttlSecondsAfterFinished: 100
...

clean cron job

...
spec:
  schedule: "*/1 * * * *"
  successfulJobsHistoryLimit: 0
  failedJobsHistoryLimit: 0
...
apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox:1.28
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure
$ kubectl create -f https://k8s.io/examples/application/job/cronjob.yaml
$ kubectl get cronjob hello
NAME    SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
hello   */1 * * * *   False     0        <none>          10s

$ kubectl get cronjob hello
NAME    SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
hello   */1 * * * *   False     0        50s             75s


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


$ kubectl delete cronjob hello

SUSPEND JOB

Since Kubernetes API lacked the ability to suspend and resume Jobs in automated manner based on priority, it boils down to manual effort to set the priority of the job which needs to be run first. We have two option:

  • delete the lower priority job so that the high priority job can run or
  • just keep all the low priority jobs in suspend state till all the other higher priority job completes.
$ kubectl patch cronjobs <job-name> -p '{"spec" : {"suspend" : true }}'
$ kubectl patch cronjobs <job-name> -p '{\"spec\" : {\"suspend\" : true }}'

# To suspend all the cronjobs at one go 
$ kubectl get cronjobs | grep False | cut -d' ' -f 1 | xargs kubectl patch cronjobs -p '{"spec" : {"suspend" : true }}'

$ kubectl get cronjobs
NAME  SCHEDULE     SUSPEND ACTIVE LAST   SCHEDULE  AGE
hello */1 * * * *  True      5    15m30s           20m12s
test  */3 * * * *  True      5    15m40s           17m52s


# bring back the jobs in active state
$ kubectl patch cronjobs hello -p '{"spec" : {"suspend" : false }}'
⚠️ **GitHub.com Fallback** ⚠️