How to run kubernetes cronjob immediately

9/2/2020

Im very new to kubernetes ,here i tired a cronjob yaml in which the pods are created at every 1 minute.

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure

but the pods are created only after 1 minute.is it possible to run job immediately and after that every 1 minute ?

-- june alex
cron
kubernetes
kubernetes-cronjob

1 Answer

9/3/2020

As already stated in the comments CronJob is backed by Job. What you can do is literally launch Cronjob and Job resources using the same spec at the same time. You can do that conveniently using helm chart or kustomize.

Alternatively you can place both manifests in the same file or two files in the same directory and then use:

kubectl apply -f <file/dir>

With this workaround initial Job is started and then after some time Cronjob. The downside of this solution is that first Job is standalone and it is not included in the Cronjob's history. Another possible side effect is that the first Job and first CronJob can run in parallel if the Job cannot finish its tasks fast enough. concurrencyPolicy does not take that Job into consideration.

From the documentation:

A cron job creates a job object about once per execution time of its schedule. We say "about" because there are certain circumstances where two jobs might be created, or no job might be created. We attempt to make these rare, but do not completely prevent them.

So if you want to keep the task execution more strict, perhaps it may be better to use Bash wrapper script with sleep 1 between task executions or design an app that forks sub processes after specified interval, create a container image and run it as a Deployment.

-- acid_fuji
Source: StackOverflow