Understanding jobs and CronJobs
In this section, we will learn how to use Kubernetes jobs to build temporary pods that do certain tasks. CronJobs are similar to jobs, but they run tasks according to a set schedule.
Jobs
A job launches one or more pods and continues to try executing them until a specific number of them succeed. The job keeps track of how many pods have been completed successfully. The task (that is, the job) is completed when a certain number of successful completions is met.
When you delete a job, it also deletes all the pods it created. Suspending a job causes all the current pods to be deleted until the job is resumed. The following code shows a job config that runs every minute and prints example Job Pod is Running
as its output:
apiVersion: batch/v1 kind: Job metadata: name: example-job spec: template: spec: containers: - name: example-job image: busybox command: ['echo', 'echo example Job Pod is Running'] restartPolicy: OnFailure backoffLimit: 4
The most commonly used kubectl
commands concerning jobs are as follows:
- The
create
orapply
command creates the pod:kubectl apply -f FILENAME.
For example, the kubectl apply -f ./jobs-deployment.yaml
command will create new jobs from the jobs-deployment.yaml
YAML file.
- The
describe jobs
command indicates the details of the jobs:kubectl describe jobs <<job name>>
CronJob
A CronJob is a job that is created regularly. It is equivalent to a single line in a crontab (cron table) file. It executes a job that is written in Cron format regularly.
CronJobs are used to automate common processes such as backups and report generation. You can decide when the work should begin within that period by setting each of those jobs to repeat indefinitely (for example, once a day, week, or month).
The following is an example of a CronJob that prints the example-cronjob Pod is Running
output every minute:
apiVersion: batch/v1 kind: CronJob metadata: name: example-cronjob spec: schedule: "*/1 * * * *" jobTemplate: spec: template: spec: containers: - name: example-cronjob image: busybox imagePullPolicy: IfNotPresent command: - /bin/sh - -c - date; echo example-cronjob Pod is Running ; sleep 5 restartPolicy: OnFailure
Here, schedule: /1 *
indicates that the crontab syntax is used in Linux systems.
Jobs and CronJobs are critical components of Kubernetes, particularly for performing batch processes and other critical ad hoc tasks. We'll examine service abstraction in the next section.