Create a CronJob workload

更新时间:
复制 MD 格式

A CronJob is a workload that creates Job objects on a recurring schedule. It does not manage Pods directly. Instead, it periodically creates and monitors independent Job instances based on a specified policy. CronJobs are suitable for periodic operations, such as performing backups or sending emails. This topic describes how to create a CronJob using the ACK console or kubectl.

Important

The example in this topic uses a public image. To pull the image, your cluster or nodes must have Internet access. You can use one of the following methods:

  • Enable Internet access for a cluster (Recommended): Create a public NAT gateway for the VPC that hosts the cluster. This allows all resources in the cluster to access the Internet.

  • Assign a static public IP address to nodes: A node with a public IP address can pull public images. However, you must assign a public IP address to each node where the workload is deployed.

Create a CronJob

Use the console

  1. Log on to the ACK console. In the left navigation pane, click Clusters.

  2. On the Clusters page, click the name of your cluster. In the left navigation pane, click Workloads > CronJobs.

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

  4. On the Basic Information page, configure the basic information for the application. Then, click Next to go to the Container page.

  5. In the General area, for Image Name, enter registry.cn-hangzhou.aliyuncs.com/acs-sample/nginx:latest. In the Lifecycle area, for Start > Command, enter /bin/sh, and for Parameter, enter ["-c", "echo 'starting...'; COUNTER=0; while [ $COUNTER -lt 5 ]; do sleep 2; COUNTER=$((COUNTER+1)); echo $COUNTER; done; echo 'finished'; exit 0"]. Then, click Next to open the Advanced Configuration wizard page.

    Important

    Before you pull the registry.cn-hangzhou.aliyuncs.com/acs-sample/nginx:latest image, you need to enable public network access for the cluster. If you kept the default selection for Configure SNAT for VPC when you created the cluster, the cluster already has public network access. If you did not select it, see Enable public network access for a cluster.

  6. On the Advanced Settings page, you can configure the schedule and job settings for the CronJob. In this example, set the schedule to run every 2 minutes and keep the other options at their default values. Then, click Launch at the bottom of the page.

    Category

    Parameter

    Description

    CronJobs

    Schedule

    The schedule for running the Job. You can set the schedule by hour, day, week, month, or a cron expression.

    For more information about cron expressions, see Cron Expressions.

    Concurrency Policy

    Specifies whether a new Job can be created while the previous Job is still running.

    • Forbid: Skips creating a new Job. This is suitable for scenarios where Jobs must run in a specific order or have dependencies.

    • Allow: Allows concurrent runs by creating a new Job immediately. This is suitable for scenarios where Jobs do not affect each other.

    • Replace: Terminates the current Job and creates a new one. This is suitable for scenarios where you need only the latest execution results.

    Job History

    The number of successful and failed Job instances to retain. This prevents excessive history from consuming resources.

    • Successful Jobs History Limit: The number of the most recent successful Job instances to retain.

    • Failed Jobs History Limit: The number of the most recent failed Job instances to retain.

    Job Settings

    Completions

    jobTemplate.spec.completions: Specifies the number of Pods that must run to completion.

    Parallelism

    jobTemplate.spec.parallelism: Specifies the number of Pods that can run concurrently.

    Timeout

    jobTemplate.spec.activeDeadlineSeconds: The maximum runtime for a single Job. The Job is immediately stopped if it exceeds this value, regardless of its completion status. This is useful for tasks with strict deadlines or for those that might enter an infinite loop. The default value is 600 seconds (s).

    BackoffLimit

    jobTemplate.spec.backoffLimit: The maximum number of retries for failed Pods. This is the total number of failures across all Pods. The default value is 6.

    Restart

    jobTemplate.spec.template.spec.restartPolicy, which specifies the restart policy after a Pod fails.

    • Never: If a container exits with an error, the Pod is marked as Failed and is not restarted. This failure counts towards the Job's backoffLimit.

    • On Failure: If a container exits with an error, it is restarted by the kubelet within the same Pod. These restarts do not count towards the Job's backoffLimit.

    Labels and Annotations

    Pod labels

    Adds a Pod label to each Pod created by the workload. Resources in the cluster, such as workloads and Services, are matched with Pods through labels. ACK adds a label in the format app:<application-name> to each Pod by default.

    Pod Annotations

    Adds a Pod annotation to each Pod created by the workload. Some features in ACK use annotations, which you can edit when using those features.

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

    The status of each Job shows "1 Succeeded, 0 Failed", confirming that the CronJob is running as scheduled.

Use kubectl

Important

Before creating the workload, ensure that you are connected to your cluster using kubectl. For more information, see Obtain the kubeconfig file of a cluster and use kubectl to connect to the cluster.

  1. Copy the following YAML file and save it as cronjob.yaml. The jobTemplate.spec section of a CronJob has the same format as the spec of a Job. The following example uses the Job example from Create a Job workload.

    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: example-cronjob
      labels:
        app: cronjob
    spec:
      schedule: "*/2 * * * *" # Run the Job every 2 minutes.
      concurrencyPolicy: Forbid # Forbid concurrent runs.
      successfulJobsHistoryLimit: 3 # Retain the 3 most recent successful Jobs.
      failedJobsHistoryLimit: 2     # Retain the 2 most recent failed Jobs.
      jobTemplate:
        spec:
          completions: 1 # The Job is considered complete after one Pod runs to completion.
          parallelism: 1 # Run only 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 # If a container fails, mark the Pod as Failed and do not restart it.
  2. Run the following command to create the CronJob:

    kubectl apply -f cronjob.yaml

    Expected output:

    cronjob.batch/example-cronjob created
  3. Wait for about 10 minutes and run the following command to check the Job status:

    kubectl get job

    Expected output:

    NAME                       COMPLETIONS   DURATION   AGE
    example-cronjob-2901****   1/1           31s        5m13s
    example-cronjob-2901****   1/1           31s        3m13s
    example-cronjob-2901****   1/1           26s        73s

Related topics