How can I specify cron timezone in k8s cron job?

8.8k views Asked by At

According to documentation (https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/) I can create cron job in k8s with specify timezone like: "CRON_TZ=UTC 0 23 * * *"

My deployment file is:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: scheduler
spec:
  schedule: "CRON_TZ=UTC 0 23 * * *"
...

During the deploy I am getting an error:

The CronJob "scheduler" is invalid: spec.schedule: Invalid value: "CRON_TZ=UTC 0 23 * * *": Expected exactly 5 fields, found 6: CRON_TZ=UTC 0 23 * * *

Cron is working without perfectly timezone (schedule: "0 23 * * *")

Cluster version is: Kubernetes 1.21.2-do.2 - digitalocean.

What is wrong?

1

There are 1 answers

3
Martijn Pieters On

The CRON_TZ=<timezone> prefix won't be available yet, not until 1.22. The inclusion in the 1.21 release docs was an error.

Originally, the change adding the syntax was included for 1.22, but it appears someone got confused and moved the documentation over to 1.21. Supporting the CRON_TZ=<timezone> syntax is accidental, purely because the package used to handle the scheduling was recently upgraded to version 3, which added support for the syntax. The package is the key component that makes the syntax possible and is only part of 1.22.

As of November 2021 the wording in the documentation has been adjusted to state that CRON_TZ is not officially supported:

Caution:

The v1 CronJob API does not officially support setting timezone as explained above.

Setting variables such as CRON_TZ or TZ is not officially supported by the Kubernetes project. CRON_TZ or TZ is an implementation detail of the internal library being used for parsing and calculating the next Job creation time. Any usage of it is not recommended in a production cluster.

If you can upgrade to 1.24, you can instead use the new CronJobTimeZone feature gate to enable the new, official, time-zone support added with KEP 3140. Note that this is still an alpha-level feature; hopefully it will reach beta in 1.25. If all goes well, the feature should reach maturity in release 1.27.

With the feature-gate enabled, you can add a timeZone field to your CronJob spec:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: scheduler
spec:
  schedule: "0 23 * * *"
  timeZone: "Etc/UTC"