Video Thumbnail for Lesson
4.7: CronJob

CronJob

In Kubernetes, a CronJob creates Jobs on a time-based schedule.

CronJobs are useful for running periodic and recurring tasks, such as backups, report generation, and other repetitive jobs.

Hands-On: Working with CronJobs

We will create and examine a CronJob to understand it's behavior.

1. Create a Namespace for the Examples

First, we'll create a namespace for these examples and set it as the default.

# task 01-create-namespace
# - Create a namespace for these examples and set as default
kubectl apply -f Namespace.yaml
kubens 04-cronjob

2. Apply the CronJob Configuration

We can then apply our CronJob configuration to the cluster.

# CronJob.echo-date-better.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: echo-date-better
  namespace: 04--cronjob
spec:
  schedule: "* * * * *"
  jobTemplate:
    spec:
      parallelism: 1
      completions: 1
      activeDeadlineSeconds: 100
      backoffLimit: 1
      template:
        metadata:
          labels:
            app: echo-date
        spec:
          containers:
            - name: echo
              image: busybox:1.36.1
              command: ["date"]
          restartPolicy: Never

You will notice that everything in the spec.jobTemplate portion matches the configuration we used for the Job in the previous lesson.

The CronJob adds the schedule field, which allows us to specify when the job should run in the form of a cron expression string.

To learn more about cron strings and validate your own, I suggest using https://crontab.guru/!

3. Manually Create a Job from a CronJob

Because we specified the schedule as "* * * * *", each minute, Kubernetes will create a Job which in turn will create a Pod to execute.

In most scenarios the schedule is something much less infrequent, so it can be useful to manually create a Job from the CronJob specification for testing purposes.

# task 04-create-job-from-cronjob
# - Manually create a job using a cronjob as the template
kubectl create job --from=cronjob/echo-date-better manually-triggered
❯ kubectl get jobs
NAME                 STATUS     COMPLETIONS   DURATION   AGE
manually-triggered   Complete   1/1           6s         6s
❯ kubectl get pods
NAME                       READY   STATUS      RESTARTS   AGE
manually-triggered-w5lkf   0/1     Completed   0          9s

5. Delete the Namespace to Clean Up

Finally, clean up by deleting the namespace, which will also delete all resources within it.

# task 05-delete-namespace
# - Delete the namespace to clean up
kubectl delete -f Namespace.yaml