CronJob运行自动化任务
创建
创建一个cronjob,每一分钟输出日期和指定信息
cronjob.yml
yaml
apiVersion: batch/v1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
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
创建
powershell
root@k8s-master:~# vim cronjob.yml
root@k8s-master:~# kubectl apply -f cronjob.yml
cronjob.batch/hello created
获取状态
powershell
root@k8s-master:~# kubectl get cronjob
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
hello */1 * * * * False 0 <none> 24s
CronJob 还没有调度或执行任何任务。大约需要一分钟任务才能创建好。
powershell
root@k8s-master:~# kubectl get jobs --watch
NAME COMPLETIONS DURATION AGE
hello-28293226 1/1 2s 2m8s
hello-28293227 1/1 1s 68s
hello-28293228 1/1 2s 8s
看到了一个运行中的任务被 "hello" CronJob 调度。 你可以停止监视这个任务,然后再次查看 CronJob 就能看到它调度任务
root@k8s-master:~# kubectl get cronjob
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE
hello */1 * * * * False 0 19s 4m49s
可以看到当前有0个活跃的任务,意味着任务执行完毕或者执行失败。
查看运行的Pod
powershell
root@k8s-master:~# kubectl get pod | grep hello
hello-28293233--1-m9bzx 0/1 Completed 0 2m7s
hello-28293234--1-czd7t 0/1 Completed 0 67s
hello-28293235--1-jh7l5 0/1 Completed 0 7s
powershell
root@k8s-master:~# kubectl logs hello-28293233--1-m9bzx
Wed Oct 18 01:53:01 UTC 2023
Hello from the Kubernetes cluster
删除
使用名称删除
powershell
root@k8s-master:~# kubectl delete cronjob hello
cronjob.batch "hello" deleted