kubernetes-handbook/concepts/cronjob.md

64 lines
1.8 KiB
Markdown
Raw Normal View History

2017-05-14 19:39:33 +08:00
# CronJob
2017-05-14 19:08:56 +08:00
CronJob即定时任务就类似于Linux系统的crontab在指定的时间周期运行指定的任务。在Kubernetes 1.5使用CronJob需要开启`batch/v2alpha1` API即`--runtime-config=batch/v2alpha1`。
## CronJob Spec
- `.spec.schedule`指定任务运行周期,格式同[Cron](https://en.wikipedia.org/wiki/Cron)
- `.spec.jobTemplate`指定需要运行的任务,格式同[Job](job.md)
- `.spec.startingDeadlineSeconds`指定任务开始的截止期限
- `.spec.concurrencyPolicy`指定任务的并发策略支持Allow、Forbid和Replace三个选项
```yaml
apiVersion: batch/v2alpha1
kind: CronJob
metadata:
name: hello
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: hello
image: busybox
args:
- /bin/sh
- -c
- date; echo Hello from the Kubernetes cluster
restartPolicy: OnFailure
```
2017-05-19 18:12:54 +08:00
```Bash
2017-05-14 19:08:56 +08:00
$ kubectl create -f cronjob.yaml
cronjob "hello" created
```
当然,也可以用`kubectl run`来创建一个CronJob
2017-05-19 18:12:54 +08:00
```bash
2017-05-14 19:08:56 +08:00
kubectl run hello --schedule="*/1 * * * *" --restart=OnFailure --image=busybox -- /bin/sh -c "date; echo Hello from the Kubernetes cluster"
```
2017-05-19 18:12:54 +08:00
```bash
2017-05-14 19:08:56 +08:00
$ kubectl get cronjob
NAME SCHEDULE SUSPEND ACTIVE LAST-SCHEDULE
hello */1 * * * * False 0 <none>
$ kubectl get jobs
NAME DESIRED SUCCESSFUL AGE
hello-1202039034 1 1 49s
$ pods=$(kubectl get pods --selector=job-name=hello-1202039034 --output=jsonpath={.items..metadata.name} -a)
$ kubectl logs $pods
Mon Aug 29 21:34:09 UTC 2016
Hello from the Kubernetes cluster
# 注意删除cronjob的时候不会自动删除job这些job可以用kubectl delete job来删除
$ kubectl delete cronjob hello
cronjob "hello" deleted
```