Creating Kubernetes k8s Cronjob Schedule Expression Example

Posted April 25, 2024
Creating Kubernetes k8s Cronjob Schedule Expression Example

This guide teaches you how to create Kubernetes CronJobs. You will learn how to correctly the Kubernetes cron job schedule formats. This way, Kubernetes will run your jobs based on what your scheduler says. When working with Cronjobs and Kubernetes, you need to get your CronJob Schedule Expressions right. Kubernetes CronJobs runs Jobs at intervals.

A CronJob schedule gets created using a cron expression with the correct format. This way your CronJob scheduler consists of five fields representing minute, hour, day of the month, month, and day of the week, respectively.

Now, get buckle up and get ready to create Kubernetes k8s Cronjob Schedule Expression Examples like a Pro.

Creating a k8s Cronjob Schedule Expression Example

Let’s say you have a simple CronJob. Here you have an example of a Kubernetes CronJob schedule expression that¬†is every 10 minutes. In this case, you will schedule it with a CronJob expression as "*/10 * * * *". It will be represented as follows:

apiVersion: batch/v1
kind: CronJob
metadata:
 name: apache-cronjob
spec:
 schedule: "*/10 * * * *"
 jobTemplate:
  spec:
   template:
    spec:
     containers:
     - name: apache-container
      image: apache:latest
      ports:
      - containerPort: 80
     restartPolicy: OnFailure

How to arrive at this CronJob schedule format? This "*/10 * * * *" looks like an Expression that you must get it correctly.

Understanding the CronJob Schedule Expressions

In your CronJob schedule expressions, each field has a

  • value,
  • range of values,
  • list of values separated by commas,
  • an asterisk (*) to indicate all possible values.

This format will summarized in a cron expression as follows:

<Minute> <Hour> <Day_of_the_Month> <Month> <Day_of_the_Week>

Each Cron Expression is diffent. Take a closer example of dates. A month can have 30 days but a week will only have 7 days. In this case, the expression will be represented as follows:

  • Minute (0-59) This means only acceptable values are 0 to 59.
  • Hour (0-23) at which the job will run. Acceptable values are 0 to 23.
  • Day of the Month¬†Acceptable values are 1 to 31
  • Month values are 1 to 12 or the abbreviated names of months (e.g., Jan, Feb, …).
  • Day of the Week values are 0 to 7 (where both 0 and 7 represent Sunday) or the abbreviated names of days (e.g., Sun, Mon, …).

Designing a Kubernetes CronJob Schedule Expression

The main task is to get your schedule correct. That means the expression format must align to the exact time based on your expression format.

Assume you want to run the CronJob every day at midnight. In this case, the expression will be simple as follows:

0 0 * * *

You only need to represent minutes and hours based on the midnight clock format. However, you might need a more specific time. Let’s say 30 minutes. In this way, minutes range from 0 to 59.

Take this expression format:

<Minute> <Hour> <Day_of_the_Month> <Month> <Day_of_the_Week>

To represent 3o minutes you will use:

*/30 * * * *

This means:

  • Every 30 minutes the task will run when the minute is divisible evenly by 30.
  • The remaining fields * * * * are set to asterisks (*). This means your CronJob will be executed every hour, day, month, and day of the week. But, as long as it is after every 30-minute mark from the time you run your Cron.

Now, this expression opens another section to learn more about these Special Characters.

How to use Kubernetes CronJob Schedule Expression Special Characters

Any CronJob Schedule Expression will work with these Characters:

  • Asterisk (*) to represent all possible values within a field. ¬† For example, * * * * * means every minute, every hour, every day, every month, every day of the week.
  • Comma (,) to add multiple values in a field.

For example, 1,15,30 * * * * for minutes 1, 15, and 30 of every hour.

  • Hyphen (-) to create a range of values in a field.

Here is a good one: 10-20 * * * * to schedule every minute from 10 through 20.

  • Slash (/)¬†to include increments of values.

Let’s say */15 * * * * to schedule a CronJob every 15 minutes.

Combining the CronJob Expression Fields

You will combine all the above fields to create any complex Kubernetes CronJob while making sure you have the right Schedule Expression formats. Check these examples:

  • 0 0 * * *: Runs daily at midnight.
  • 0 3 * * 1 gets provoked every Monday at 3 AM.
  • 0 12 1 * *: is executed on the 1st day of every month at noon.
  • 0 * * * *: for every hour.

To narrow it down to an even more complex expression, you can have:

  • */5 * * * * scheduler for every 5 minutes.
  • 0 0 * * 6 to schedule at midnight every Saturday.
  • */15 9-17 * * 1-5 to run Kubernetes Cron every 15 minutes during business hours (9 AM to 5 PM) on weekdays.
  • 0,30 0 * 10,20,30 * * to excute a cron every 30 minutes on the 10th, 20th, and 30th of each month.

Fineturning Kubernetes CronJob Schedule

Kubernetes will use .spec.jobTemplate to create jobs and your schedule. It here you will add advanced scheduling features to ensure the set task runs as expected.

Let’s, for example, say a given job has missed its configured deadline. This will be a failed job, right?

You don’t want that to happen as it will affect how your cron works. In this Kubernetes will let you use optional fields.

A .spec.startingDeadlineSeconds will add a deadline to which Kubernetes must refer to a job as failed. Other options will be:

  • concurrencyPolicy to check how concurrent executions of the job should be handled. For example (1)Allow allows concurrent executions, while (1)Forbid ensures only one job runs at a time, and (1) Replace replaces the currently running job with a new one if a new execution is triggered.
  • successfulJobsHistoryLimit sets the maximum number of successful job completions to retain.
  • failedJobsHistoryLimit sets the maximum number of failed job completions to retain.
  • suspend to let Kubernetes know whether the CronJob is initially suspended (true or false). When true, the CronJob won’t create new Jobs based on the schedule until it is manually resumed. The default value is false. ¬† You will represent these optional fields and ensure your scheduler as follows:
apiVersion: batch/v1
kind: CronJob
metadata:
 name: apache-cronjob
spec:
 schedule: "*/10 * * * *" # Runs every 10 minutes
 startingDeadlineSeconds: 60 # Job should start within 1 minute of the scheduled time
 concurrencyPolicy: Allow # concurrent executions of the job
 successfulJobsHistoryLimit: 3 # Retain the history of the last 3 successful job completions
 failedJobsHistoryLimit: 3 # Retain the history of the last 3 failed job completions
 suspend: false # whether the cron job is initially suspended (default: false)
 jobTemplate:
  spec:
   template:
    metadata:
     labels:
      app: apache-cronjob
    spec:
     containers:
     - name: apache-container
      image: apache:latest
      ports:
      - containerPort: 80
     restartPolicy: OnFailure

Related: How to Run, Apply, Get Kubernetes CronJob with Kubectl

kubectl apply -f cronjob.yaml

Your deployed Kubernetes CronJob should have these fields set. Check this using the following command:

kubectl describe cronjob apache-cronjob

Creating Kubernetes k8s Cronjob Schedule Expression Example

Creating Kubernetes k8s Cronjob Schedule Expression Example

Conclusion

This is all you need to create Kubernetes CronJobs. I hope you are now able to create any Kubernetes CronJob scheduler and add the correct expression formats.

Creating Kubernetes k8s Cronjob Schedule Expression Example

Written By:

Joseph Chege