cong
cong

Reputation: 61

How Can I set Kubernetes Cronjob to run at a specific time

When I set the Cronjob Schedule as */1 * * * *,it would work.

When I set any number which is in 0-59 to the crontab minute,such as 30 * * * *,it would work as well.

However when I set the Cronjob Schedule as 30 11 * * *,it even doesn`t create a job at 11:30.

All the config is followed:

 apiVersion: batch/v1beta1
 kind: CronJob
 metadata:
   name: hello
 spec:
   schedule: "33 11 * * *"
   jobTemplate:
     spec:
       template:
         spec:
           containers:
             - name: hello-cronjob
               image: busybox
               command: ["bash","-c","date;echo  Hello from the Kubernetes cluste"]
           restartPolicy: OnFailure

Upvotes: 3

Views: 4612

Answers (2)

Harsh Manvar
Harsh Manvar

Reputation: 30083

Try this once and test result

0 30 11 1/1 * ? *

http://www.cronmaker.com/

You might face the Timezone issue based on the Nodes running in different region, so take care accordingly.

Can leverage the K8s 1.27 Timezone field in cronjob

๐“๐ข๐ฆ๐ž๐™๐จ๐ง๐ž ๐Ÿ๐จ๐ซ ๐‚๐ซ๐จ๐ง๐ฃ๐จ๐›๐ฌ โ€” Stable

Starting with version 1.24, CronJob includes the option to select the ๐“๐ข๐ฆ๐ž๐™๐จ๐ง๐ž, with 1.27 itโ€™s moving to stable. Previously job is scheduled by a cron job based on the time zone that the ๐ค๐ฎ๐›๐ž-๐œ๐จ๐ง๐ญ๐ซ๐จ๐ฅ๐ฅ๐ž๐ซ-๐ฆ๐š๐ง๐š๐ ๐ž๐ซ is currently running.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: tz-test
spec:
  timeZone: 'Asia/Calcutta'
  schedule: "0 21 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: tz-test
            image: busybox
            command:
            - /bin/sh
            - -c
            - date; echo hello world!
          restartPolicy: OnFailure

Upvotes: 1

Crou
Crou

Reputation: 11388

This is probably because your cluster is running in a different timezone then the one used by you.

You can check what timezone will be set in a POD using:

kubectl run -i --tty busybox --image=busybox --restart=Never -- date.

As for your yaml it looks good, there is no need to change anything with the spec.schedule value.

A small hint that might be helpful to you which is checking the logs from Jobs.

When you create CronJob when it's scheduled it will spawn a Job, you can see them using kubectl get jobs.

$ kubectl get jobs
NAME               DESIRED   SUCCESSFUL   AGE
hello-1552390680   1         1            7s

If you use the name of that job hello-1552390680 and set it as a variable you can check the logs from that job.

$ pods=$(kubectl get pods --selector=job-name=hello-1552390680 --output=jsonpath={.items..metadata.name})

You can later check logs:

$ kubectl logs $pods
Tue Mar 12 11:38:04 UTC 2019
Hello from the Kubernetes cluster

Upvotes: 3

Related Questions