How to Create Jobs and CronJobs on Kubernetes

In this blog, we will see how to create Jobs and CronJobs on Kubernetes.

Do you know what is Jobs and CronJobs on Kubernetes?

If you don’t know don’t worry I will give you a quick review of Jobs and CronJobs in Kubernets.

Jobs – Jobs are objects of Kubernetes that do not run continuously like other Kubernetes objects it runs until the tasks given to them are executed and get terminated.

CronJobs – CronJobs are also an object of Kubernetes which schedules tasks to run with a scheduled time gap, it is mostly used for repetitive tasks such as cleaning temporary files, backups, etc.

A simple example of how to create Jobs and CronJobs on Kubernetes is given below

First, let’s see about creating Jobs on Kubernetes.

Create Jobs

To create a Job, first, create a manifest file job.yaml and copy the below content into it

apiVersion: batch/v1
kind: Job
metadata:
  name: job
spec:
  template:
    spec:
      containers:
      - name: container
        image: busybox
        command: ["echo", "Hello, Kubernetes!"]
      restartPolicy: Never

Run the following command to create a Job

kubectl apply -f job.yaml 

This will create a Job on the default namespace, which runs the echo command on the busybox container and gets terminated as shown below

How Jobs gets executed on kubernets

Create CronJobs

Now, let’s see how to create CronJobs on Kubernetes.

To create a Job, first, create a manifest file cronjob.yaml and copy the below content into it

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cronjob
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: container
            image: busybox
            command: ["echo", "Hello, Kubernetes!"]
          restartPolicy: Never

Run the following command to create a Job

kubectl apply -f cronjob.yaml 

This will create a CronJob on the default namespace which schedules the command to run every 1 minute as shown below

How CronJobs runs tasks

Conclusion

In this blog, you have learned about how to create Jobs and CronJobs and how they run tasks on Kubernetes.

I hope this blog gives a basic understanding of Kubernetes Jobs and CronJobs.

Other Interesting Blogs

Leave a Comment

Share via
Copy link
Powered by Social Snap