All Products
Search
Document Center

Container Service for Kubernetes:Create CronJob workloads for scheduled tasks

Last Updated:Mar 26, 2026

A CronJob periodically creates Jobs on a defined schedule and tracks their status — it doesn't manage Pods directly. Use CronJobs for recurring tasks such as database backups, report generation, or sending emails.

This topic shows how to create a CronJob using the ACK console or kubectl.

Important

The sample images in this topic are public images. Your cluster must have Internet access to pull them. Choose one of the following options:

  • [Enable Internet access for an existing cluster](https://www.alibabacloud.com/help/en/document_detail/178480.html) (recommended): Create a public NAT gateway for the virtual private cloud (VPC) hosting the cluster. All cluster resources gain Internet access.

  • [Assign static public IPs to nodes](https://www.alibabacloud.com/help/en/document_detail/2858287.html): Nodes with public IPs can pull public images, but every node that runs the workload must have a public IP assigned.

Prerequisites

Before you begin, ensure that you have:

Create a CronJob using the console

  1. Log in to the ACK console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, click the name of the target cluster. In the left-side pane, choose Workloads > CronJobs.

  3. On the CronJobs page, click Create from Image.

  4. On the Basic Information wizard page, configure the basic parameters, then click Next to go to the Container wizard page.

  5. In the General section, set Image Name to registry.cn-hangzhou.aliyuncs.com/acs-sample/nginx:latest. In the Lifecycle section, configure the Start parameter: Click Next to go to the Advanced wizard page.

    • Command: /bin/sh

    • Parameter: ["-c", "echo 'starting...'; COUNTER=0; while [ $COUNTER -lt 5 ]; do sleep 2; COUNTER=$((COUNTER+1)); echo $COUNTER; done; echo 'finished'; exit 0"]

    Important

    Before pulling registry.cn-hangzhou.aliyuncs.com/acs-sample/nginx:latest, make sure the cluster has Internet access. If you selected Configure SNAT for VPC when creating the cluster, Internet access is already enabled. Otherwise, see Enable Internet access for an existing cluster.

    image.png

  6. On the Advanced wizard page, configure the scheduling and job settings. For this example, set the schedule to run every 2 minutes and leave all other options at their defaults. Click Create. The following tables describe the key parameters on this page.

    CronJob settings

    Parameter Description
    Schedule How often the CronJob runs. Set a preset frequency (hourly, daily, weekly, or monthly) or enter a custom cron expression. The five fields map to: minute hour day-of-month month day-of-week. See Cron expression syntax below.
    Concurrency policy What happens when a new Job is scheduled while the previous one is still running. Forbid skips the new Job (use this when jobs must run in sequence or depend on each other). Allow starts the new Job immediately (use this when jobs are independent). Replace terminates the running Job and starts a new one (use this when only the latest result matters).

    Job history

    Parameter Description
    Successful Jobs History Limit Number of recent successful Jobs to retain. Older records are deleted to avoid excessive resource usage.
    Failed Jobs History Limit Number of recent failed Jobs to retain.

    Job settings

    Parameter Kubernetes field Description Default
    Completions jobTemplate.spec.completions Number of Pods that must reach the completed state for the Job to succeed.
    Parallelism jobTemplate.spec.parallelism Maximum number of Pods running concurrently.
    Timeout jobTemplate.spec.activeDeadlineSeconds Maximum runtime for a single Job execution. The Job is stopped immediately when this limit is reached, regardless of completion status. Suitable for jobs with strict time requirements or that may loop indefinitely. 600 seconds
    BackoffLimit jobTemplate.spec.backoffLimit Maximum number of retries across all Pods before the Job is marked as failed. 6
    Restart jobTemplate.spec.template.spec.restartPolicy Restart behavior when a Pod fails. Never restarts the container in place without creating a new Pod (restarts don't count toward backoffLimit). On Failure creates a new Pod to replace the failed one.

    Labels, annotations

    Parameter Description
    Pod Labels Labels added to each Pod. ACK adds an app: <application-name> label by default. Labels are used to match Pods to workloads and services.
    Pod Annotations Annotations added to each Pod. Some ACK features rely on specific annotations — configure these when enabling those features.

    image.png

  7. After the CronJob is created, Jobs appear in the console at 2-minute intervals.

    image.png

Create a CronJob using kubectl

Important

Connect to the cluster via kubectl before proceeding. See Connect to a cluster via kubectl.

  1. Save the following YAML as cronjob.yaml. The jobTemplate.spec section uses the same structure as a standalone Job spec.

    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: example-cronjob
      labels:
        app: cronjob
    spec:
      schedule: "*/2 * * * *"           # Run every 2 minutes
      concurrencyPolicy: Forbid          # Skip new Job if previous one is still running
      successfulJobsHistoryLimit: 3      # Keep the 3 most recent successful Jobs
      failedJobsHistoryLimit: 2          # Keep the 2 most recent failed Jobs
      jobTemplate:
        spec:
          completions: 1                 # Job succeeds after 1 Pod completes
          parallelism: 1                 # Run one Pod at a time
          template:
            spec:
              containers:
              - name: counter
                image: anolis-registry.cn-zhangjiakou.cr.aliyuncs.com/openanolis/nginx:1.14.1-8.6
                command:
                - /bin/sh
                - -c
                - |
                  echo "starting...";
                  COUNTER=0;
                  while [ $COUNTER -lt 5 ]; do
                    sleep 2;
                    COUNTER=$((COUNTER+1));
                    echo "${COUNTER}";
                  done;
                  echo "finished";
                  exit 0
              restartPolicy: Never       # Do not restart the Pod on failure
  2. Apply the manifest:

    kubectl apply -f cronjob.yaml

    Expected output:

    cronjob.batch/example-cronjob created

Verify the CronJob

After creating the CronJob, confirm it is running as expected.

  1. Check the CronJob schedule status:

    kubectl get cronjob example-cronjob

    Expected output:

    NAME               SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    example-cronjob   */2 * * * *   False     0        <none>          15s

    The SUSPEND column shows False, which means the CronJob is active and will trigger on schedule.

  2. Wait about 10 minutes, then check the Jobs created by the CronJob:

    kubectl get job

    Expected output:

    NAME                       STATUS     COMPLETIONS   DURATION   AGE
    example-cronjob-2901**22   Complete   1/1           31s        5m13s
    example-cronjob-2901**23   Complete   1/1           31s        3m13s
    example-cronjob-2901**24   Complete   1/1           26s        73s

    Jobs appear at 2-minute intervals and show Complete status when finished.

  3. Check the logs for a specific Job's Pod:

    # List Pods for the most recent Job
    kubectl get pods --selector=job-name=<job-name>
    
    # View logs
    kubectl logs <pod-name>

    Replace <job-name> with the name of a Job from the output above (for example, example-cronjob-2901**24). Successful output ends with finished.

Cron expression syntax

A cron expression consists of five space-separated fields:

# .---------------- minute (0–59)
# |  .------------- hour (0–23)
# |  |  .---------- day of month (1–31)
# |  |  |  .------- month (1–12)
# |  |  |  |  .---- day of week (0–6, Sunday to Saturday)
# |  |  |  |  |
  *  *  *  *  *

Common shorthand entries:

Entry Description Equivalent
@hourly Run once an hour at the start of the hour 0 * * * *
@daily (or @midnight) Run once a day at midnight 0 0 * * *
@weekly Run once a week at midnight on Sunday 0 0 * * 0
@monthly Run once a month at midnight on the first day 0 0 1 * *
@yearly (or @annually) Run once a year at midnight on January 1 0 0 1 1 *

To build and validate cron expressions interactively, use crontab.guru.

What's next