Schedule a Kubernetes cronjob to run just once

Viewed 1451

How can I schedule a Kubernetes cron job to run at a specific time and just once?

(Or alternatively, a Kubernetes job which is not scheduled to run right away, but delayed for some amount of time – what is in some scheduling systems referred to as "earliest time to run".)

The documentation says:

Cron jobs can also schedule individual tasks for a specific time [...]

But how does that work in terms of job history; is the control plane smart enough to know that the scheduling is for a specific time and won't be recurring?

2 Answers

You can always put specific minute, hour, day, month in the schedule cron expression, for example 12:15am on 25th of December:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "15 0 25 12 *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            imagePullPolicy: IfNotPresent
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure

Unfortunately it does not support specifying the year (the single * in the cron expression is for the day of the week) but you have one year to remove the cronjob before the same date & time comes again for the following year.

In case you need to schedule your job and run it only once, you can use at command in Linux, which allow to schedule commands to be executed at a particular time.

For example:

echo "kubectl create -f job.yaml" | at 08:52

Command should be added on the admin machine or on the master node.

Related