Skip to main content

Configuring CronJobs in Kubernetes

Hands-On Lab

 

Photo of Will Boyd

Will Boyd

DevOps Team Lead in Content

Length

01:00:00

Difficulty

Intermediate

Pods are not the only way to run workloads in Kubernetes. You can also use jobs to execute something once, or you can use cron jobs to execute workloads on a schedule. This lab provides an opportunity to learn about cron jobs by implementing a simple scheduled job in a working Kubernetes cluster.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Configuring CronJobs in Kubernetes

The scenario

Our company has a simple data cleanup process that is run periodically for maintenance purposes. They would like to stop doing this manually in order to save time, so we've have been asked to implement a cron job in the Kubernetes cluster that runs this process. We need to create a cron job called cleanup-cronjob using the linuxacademycontent/data-cleanup:1 image, and the job needs to run every minute.

Get logged in

Use the credentials and server IP in the hands-on lab overview page to log in with SSH.

Create the cron job in the cluster

Create a descriptor for the cron job with vi ~/cleanup-cronjob.yml, and put the following contents into it:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: cleanup-cronjob
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: data-cleanup
            image: linuxacademycontent/data-cleanup:1
          restartPolicy: OnFailure

Create the cron job in the cluster:

[user@host]$ kubectl apply -f ~/cleanup-cronjob.yml

Allow the cron job to run successfully

Give the cron job a minute or so to run once, and then check the status:

kubectl get cronjob cleanup-cronjob

You should see a timestamp under LAST-SCHEDULE, indicating the job was executed.

Conclusion

Well, it's done. We set up a cron jon in Kubernetes that runs every minute, and cleans out unwanted data. Congratulations!