a5b4383297
* fix: fix internal service filename in 08-service section * fix: typo * fix: fix markdownlint in CI * fix: typo * fix: typo * fix: `environment variables`, not `environmental` * fix: typo & missing punctuation * fix: `much` not `many` * fix: `lets` not `let's` * fix: typo * fix: typo * fix: phrasing * fix: typo * fix: typo * fix: mysql operator manifest api version got this error while trying to run it as is: error: unable to recognize "20-operators/01-mysql-operator.yml": no matches for kind "Deployment" in version "apps/v1beta1" * fix: spelling |
||
---|---|---|
.. | ||
01-simple-cronjob.yml | ||
02-simple-job.yml | ||
README.md |
README.md
Running a background process: cronjob
Introduction
In this section you will learn how to run background tasks using crons & jobs.
CronJob
Let's start with crons. Crons are like the cron in linux a time-based job scheduler.
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: simple-cronjob
spec:
schedule: "*/1 * * * *"
jobTemplate:
spec:
template:
spec:
restartPolicy: Never
containers:
- name: pi
image: perl
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(100)"]
spec
:schedule
: when to start this cron, in the same format as the linux crons.*/2 * * * *
means every 2 minutesjobTemplate
: the template of the container(s) to startcommand
: the command to run, here compute the first 100 digits of π.
Let's apply it:
$ kubectl apply -f 09-cronjob/01-simple-cronjob.yml
cronjob.batch "simple-cronjob" created
Wait a bit and access the logs of the pod created by the cron.
Job
If you need to run a one time job, you can use the Job
in Kubernetes. In fact the CronJob
will start a Job
for you at the scheduled interval.
apiVersion: batch/v1
kind: Job
metadata:
name: simple-job
spec:
template:
spec:
containers:
- name: c
image: busybox
command: ["sh", "-c", "echo Processing item $ITEM && sleep 5"]
restartPolicy: Never
This manifest is fairly close to a CronJob
.
Apply it and see what is happening. Does it restart?
$ kubectl apply -f 09-cronjob/02-simple-job.yml
job.batch "simple-job" created
If you have a long running background process - like a consumer of a queue - you can use a deployment
without a service
.
Exercises
- Transform the
simple-job
to a cron job running every 2 minutes - Transform the
simple-cronjob
in a deployment of1
replica, and compute the 1_000 first digits of π. What is happening when the container finishes?
Clean up
kubectl delete deployment,rs,service,cronjob,pod --all