L P
L P

Reputation: 109

kubernetes cronjob only runs once?

I created a k8s CronJob with the following schedule (run every minute):

schedule: "*/1 * * * *"

I see my CronJob created:

NAMESPACE     NAME                   READY   STATUS    RESTARTS   AGE
job-staging   job-1593017820-tt2sn   2/3     Running   0          10m

My job simply does a Printf to the log, one time, then exits.

When I do a kubernetes get cronjob I see:

NAMESPACE     NAME                   READY   STATUS    RESTARTS   AGE
job-staging   job   */1 * * * *      False   1         19m        19m

When I look at the logs, it looks like it only ran once, which was the first run. Do I need to prevent my program from exiting?

I assumed k8s would restart my program, but maybe that's a wrong assumption.

Upvotes: 2

Views: 5386

Answers (1)

guimorg
guimorg

Reputation: 95

Your assumption about the behavior of Kubernetes ("restarting the program") is correct.

As you may know, a Job is basically a Kubernetes Pod that executes some process and successfully finishes when it exits with a zero exit code. The "Cron" part of CronJob is the most obvious, scheduling the Job to execute in a particular time pattern.

Most YAML objects for CronJobs include the restartPolicy: OnFailure key that prevents Kubernetes from rescheduling the Job for a non-zero exit code (the hello-world YAML file in Kubernetes documentation uses this flag).

From what I see in the logs obtained by your kubectl instruction, it looks like your Job is failing - because of the Status 1. I would recommend you check the logs of the CronJob using kubectl logs -f -n default job-1593017820-tt2sn for any possible errors in the execution of your script (if your script explicitly exits with an exit-code, check for a possible non-zero code).

[UPDATE]

CronJobs also have limitations:

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. Therefore, jobs should be idempotent.

I think these are pretty rare scenarios, but maybe you've found yourself in these rare situations. The documentation is here.

Upvotes: 4

Related Questions