4

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?

Wytrzymały Wiktor
  • 11,492
  • 5
  • 29
  • 37
malthe
  • 1,237
  • 13
  • 25
  • 1
    Hello @malthe Are you sure want to use CronJobs, since now in Kubernetes Jobs run at once to completion and CronJobs run at specific time periodically? Can you add some details about your question: use cases, approximate time (after creation), when your job should be done? – Andrew Skorkin Oct 12 '21 at 14:19
  • @AndrewSkorkin I have tried to elaborate on the question now – basically I'm trying to achieve the equivalent of starting a washing machine for a midnight cycle without staying up until midnight to push the button. – malthe Oct 12 '21 at 17:05
  • 1
    @malthe does my answer help you to achieve what you want? yes, it does repeat but only after one year later, before which you can delete the cronjob. – Lukman Oct 12 '21 at 23:17

2 Answers2

1

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.

Lukman
  • 18,462
  • 6
  • 56
  • 66
0

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.

Andrew Skorkin
  • 1,147
  • 3
  • 11
  • This is a succint way to put it, but has some relatively major downsides such as having to parse and submit the job spec at the time of execution as well as needing a machine to be up and running at the exact time. – malthe Oct 17 '21 at 07:04
  • Yes, sure. But nonetheless, it maybe convenient, especially when there is no out-of-the-box solution from a Kubernetes CronJob. – Andrew Skorkin Oct 18 '21 at 21:00