How To Create Cronjobs In Kubernetes Cluster ?

How To Create Cronjobs In Kubernetes Cluster ?

Introduction :-

In a Kubernetes cluster, efficient job scheduling is crucial for automating repetitive tasks and maintaining the health of applications. One powerful feature Kubernetes offers for this purpose is the CronJob resource.

Basic CronJob: Let's start by creating a simple CronJob YAML file. Below is an example that runs a job every minute:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: my-cronjob
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: my-container
            image: my-image:latest
          restartPolicy: OnFailure
  • schedule: Specifies the cron schedule in standard cron format. In this example, "* * *" means every minute.

  • jobTemplate: Defines the template for the Job to be created on each cron schedule.

  • containers: Describes the container specifications, including the image to be used.

  • restartPolicy: Determines the restart policy for the pod created by the Job. "OnFailure" means it will restart only if the job fails.

Advance CronJob:- In advance cronjob there are multiple ways in which we can configure our crons.

################## WAY -1 #############
# used when url need to hit regularly after some specified time.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: demo-cronjob-hit-url-1m
  namespace: default
spec:
  concurrencyPolicy: Allow
  failedJobsHistoryLimit: 1
  jobTemplate:
    metadata:
      creationTimestamp: null
      name: demo-cronjob-hit-url-1m
    spec:
      template:
        metadata:
          creationTimestamp: null
        spec:
          containers:
            - name: demo-cronjob-hit-url-1m
              image: curlimages/curl:7.77.0
              args:
                - /bin/sh
                - -c
                - sleep 30; curl -X GET "http://google.com"
              imagePullPolicy: IfNotPresent
          restartPolicy: OnFailure
          terminationGracePeriodSeconds: 30
  schedule: "* * * * *"
  successfulJobsHistoryLimit: 1
  suspend: false
  • sleep 30: represents the cron hit every 1 min but will run after 30 sec. because sleep 30 is mentioned.
################## WAY -2 #############
# used when you need to run docker-file regularly after some specified time.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: docker-cronjob
spec:
  schedule: "0 0 * * *"  # Run every day at midnight
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: docker-container
            image: your-docker-image:latest  # Replace with your Docker image
            command: ["/bin/sh", "-c"]
            args:
            - "echo 'Running Docker container'"
          restartPolicy: OnFailure
################## WAY -3 #############
# used when you need to run python script regularly after some specified time.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: python-cronjob
spec:
  schedule: "0 0 * * *"  # Run every day at midnight
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: python-container
            image: python:3.8  # Use an appropriate Python image
            command: ["/bin/sh", "-c"]
            args:
            - "python /path/to/your/script.py"
          restartPolicy: OnFailure

Manually Stop Future Executions:

If you want to stop the future executions of a CronJob without deleting completed or failed Job pods, you can edit the CronJob to set its suspend field to true. This will prevent the CronJob from creating new Job pods.

kubectl edit cronjob <your-cronjob-name> -n <namespace>

Add or modify the suspend: true line in the YAML definition, save the changes, and exit the editor.

And you can do in one command using below :-

kubectl patch cronjob <your-cronjob-name> -p '{"spec" : {"suspend" : true }}' -n <namespace>

Conclusion:

In conclusion, leveraging CronJobs in Kubernetes allows you to automate repetitive tasks, ensuring timely execution and efficient resource utilization. Whether you're managing backup routines, data cleanup, or other periodic tasks, CronJobs provide a robust solution within the Kubernetes ecosystem.

feel free to ask queries related to this topic. I will be happy to help you.

connect with me:- / serv-ar-tistry Studio

Did you find this article valuable?

Support utkarsh srivastava's blog by becoming a sponsor. Any amount is appreciated!