kuberneteskubernetes-cronjob

how to kill/timeout a long running cronjob pod in kubernetes


Is there a way to kill a long running cronjob in kubernetes? Basically, I have created a CronJob in kubernetes. It is running a time consuming operation. I would like to put a limit on it. So, the pod associated with this cronjon should be killed/deleted automatically; if it doesn't finish up with in a specific time period say, 5 minutes.


Solution

  • To automatically terminate a Kubernetes CronJob if it doesn't finish within a specific time, such as 5 minutes, you can specify the activeDeadlineSeconds property in your job configuration. Here’s an example of how you might set this up in your CronJob YAML file:

    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: my-cronjob
    spec:
      schedule: "0 * * * *"
      jobTemplate:
        spec:
          template:
            spec:
              containers:
              - name: my-container
                image: myimage
                args:
                - /bin/sh
                - -c
                - echo Hello from the Kubernetes cluster && sleep 360
              restartPolicy: OnFailure
              activeDeadlineSeconds: 300  # This limits the job's duration to 5 minutes
    

    This configuration limits the job to run for no more than 300 seconds. If the job exceeds this limit, Kubernetes terminates the job automatically.

    For more information on how activeDeadlineSeconds works, you can checkout this page on Kubernetes Jobs. The documentation provides an in-depth explanation of job behaviors, including the use of activeDeadlineSeconds to control job execution limits.