All Products
Search
Document Center

Container Compute Service:Create a CronJob

Last Updated:Mar 26, 2026

A CronJob runs Jobs on a repeating schedule—useful for recurring tasks like database backups, report generation, or cache cleanup. Each scheduled execution creates one or more Jobs, which run the actual workload.

CronJob scheduling is approximate. Under certain conditions, a Job may be created twice or not at all. Design your Jobs to be idempotent so that running them more than once produces the same result.

Prerequisites

Before you begin, ensure that you have:

  • An Alibaba Cloud Container Service (ACS) cluster

  • Access to the ACS console or kubectl configured to connect to the cluster

To connect to your cluster using kubectl, see Obtain the kubeconfig file of a cluster and use kubectl to connect to the cluster or Use kubectl on Cloud Shell to manage ACS clusters.

Create a CronJob using the console

Step 1: Configure basic settings

  1. Log on to the ACS console. In the left-side navigation pane, click Clusters.

  2. On the Clusters page, find the target cluster and click its ID. In the left-side navigation pane of the cluster details page, choose Workloads > CronJobs.

  3. On the CronJobs page, click Create from Image in the upper-right corner.

  4. On the Basic Information wizard page, configure the following settings.

    ParameterDescription
    NameEnter a name for the CronJob.
    TypeSelect CronJob.
    LabelAdd labels to identify the application.
    AnnotationsAdd annotations to the application.
    Instance TypeSelect the instance type. For details, see ACS pod overview.
    QoS TypeSelect a QoS class. General-purpose pods support Default and BestEffort; performance-enhanced pods support Default only. For details, see Computing power QoS.
  5. Click Next.

Step 2: Configure containers

On the Container wizard page, configure the container image, resources, ports, environment variables, health checks, lifecycle hooks, volumes, and logs.

To add more containers, click Add Container to the right of the Container1 tab.

  1. In the General section, configure the basic container settings.

    ParameterDescription
    Image NameSelect an image from Container Registry Enterprise Edition, Container Registry Personal Edition, or Artifact Center. Artifact Center provides base OS images, language runtime images, and AI/big data images.
    Image Pull PolicyControls when the image is pulled. ifNotPresent (default): uses a locally cached image if available, otherwise pulls from the registry. Always: pulls from the registry on every deployment. Never: uses only locally cached images.
    Image pull secretClick Set Image Pull Secret to specify a Secret for pulling private images from Container Registry Personal Edition. Images from Container Registry Enterprise Edition can be pulled without a Secret.
    Required ResourcesSet CPU and memory requests for the container. By default, the request equals the limit, and resources are billed on a pay-as-you-go basis. If you set a limit that differs from the request in YAML, the request is automatically overridden to match the limit. For details, see Resource specifications.
    Container Start ParameterOptional. stdin: passes console input to the container. tty: associates a virtual terminal with the container's stdin, enabling interactive programs. Use both together to enable an interactive session.
    Init ContainersOptional. Select this to add an init container. Init containers run to completion before application containers start—useful for dependency checks or environment initialization. See Init containers.
  2. Optional: In the Ports section, click Add to expose container ports.

    ParameterDescription
    NameEnter a name for the port.
    Container PortSpecify a port number (1–65535).
    ProtocolSelect TCP or UDP.
  3. Optional: In the Environments section, click Add to set environment variables as key-value pairs. Supported types: Custom, Parameter, Secrets, Value/ValueFrom, and ResourceFieldRef. For more information, see Expose pod information to containers through environment variables.

  4. Optional: In the Health Check section, enable liveness, readiness, and startup probes as needed. Each probe type supports the following parameters. For configuration details, see Configure liveness, readiness and startup probes.

    • Liveness: Checks whether the container is running as expected. kubelet restarts the container after consecutive failures—useful for detecting deadlocks.

    • Readiness: Determines whether the container is ready to receive traffic. A pod is added to a Service's backend only after passing readiness checks.

    • Startup: Verifies successful container startup. Liveness and readiness probes run only after the startup probe succeeds.

    ParameterDescription
    HTTPSends an HTTP GET request. Configure the protocol (HTTP or HTTPS), path, port (1–65535), and optional custom headers.
    TCPAttempts to open a TCP socket on the specified port. The container is considered healthy if the connection succeeds.
    CommandRuns a command inside the container to check health status.
    Initial Delay (s)Wait time before the first probe runs after the container starts. Default: 3 s (HTTP), 15 s (TCP), 5 s (Command).
    Period (s)How often probes run. Default: 10 s. Minimum: 1 s.
    Timeout (s)How long before a probe times out. Default: 1 s. Minimum: 1 s.
    Healthy ThresholdConsecutive successes required to mark the container healthy. Default: 1. For liveness probes, this must be 1.
    Unhealthy ThresholdConsecutive failures required to mark the container unhealthy. Default: 3. Minimum: 1.
  5. Optional: In the Lifecycle section, configure container lifecycle hooks. For more information, see Attach handlers to container lifecycle events.

    ParameterDescription
    StartCommand that runs before the container starts.
    Post StartCommand that runs after the container starts.
    Pre StopCommand that runs before the container terminates.
  6. Optional: In the Volume section, mount volumes to the container.

    • Local storage: Select ConfigMap, Secret, or EmptyDir as the PV type, then specify the mount source and container path. See Volumes.

    • Cloud storage: Disks and File Storage NAS (NAS) file systems are supported. See Storage overview.

  7. Optional: In the Log section, configure log collection.

    ParameterDescription
    LogstoreCreate a Logstore in Log Service to store collected logs.
    Log Path in ContainerSpecify stdout to collect standard output, or enter a file path (wildcards supported, for example, /var/log/nginx).
    Custom TagAdd tags to logs on collection, for filtering and analysis.
  8. Click Next.

Step 3: Configure advanced settings

  1. In theCronJob Settings section, configure the schedule and concurrency behavior.

    ParameterDescription
    ScheduleSet when the CronJob runs—hourly, daily, weekly, monthly, or a custom cron expression. See the cron expression reference below.
    Concurrency PolicyControls what happens when a new Job is triggered while a previous Job is still running. Allow: runs Jobs concurrently (Jobs compete for cluster resources). Forbid: skips the new Job if the previous one has not finished. Replace: cancels the running Job and starts the new one.
    Job HistoryNumber of completed and failed Jobs to retain. Set to 0 to disable retention.

    Cron expression reference

    A cron expression consists of five space-separated fields:

    # ┌───────────── minute (0–59)
    # │ ┌───────────── hour (0–23)
    # │ │ ┌───────────── day of the month (1–31)
    # │ │ │ ┌───────────── month (1–12)
    # │ │ │ │ ┌───────────── day of the week (0–6, Sunday to Saturday)
    # │ │ │ │ │
    # * * * * *
    

    Examples: 0 2 * * * runs every day at 02:00. 0 9 * * 1 runs every Monday at 09:00. For the full syntax, see Cron expressions.

  2. In the Job Settings section, configure the Job execution parameters.

    ParameterDefaultDescription
    Completions1Number of pods that must complete successfully for the Job to be considered done.
    Parallelism1Maximum number of pods running in parallel at any time.
    TimeoutTime limit for the Job (activeDeadlineSeconds). If the Job does not finish within this duration, the system attempts to terminate it.
    BackoffLimit6Maximum number of retry attempts when pods fail. Failed pods are recreated with an exponential back-off delay, capped at 6 minutes.
    RestartRestart policy for containers: Never or On Failure.

    Tip: To set how late a Job can start after its scheduled time, use startingDeadlineSeconds in your YAML (this parameter is not available in the console). For example, if a backup Job runs twice a day and you set startingDeadlineSeconds: 28800, the Job can start up to 8 hours late—any later, and it waits for the next scheduled run.

  3. Optional: In the Labels,Annotations section, click Add to add labels and annotations to the pod.

  4. Click Create.

Step 4: View the CronJob

After the CronJob is created, click View Details to go to the CronJob details page.

Alternatively, on the Jobs page, click the CronJob name or click Details in the Actions column.

Create a CronJob using kubectl

The following example creates a CronJob named hello that prints a message every minute.

Key YAML parameters

ParameterDescription
.spec.scheduleCron expression defining when the Job runs. See Cron schedule syntax.
.spec.jobTemplateDefines the Job to run. See Job patterns.
.spec.startingDeadlineSecondsHow many seconds past the scheduled time the Job is still allowed to start.
.spec.concurrencyPolicyConcurrency behavior: Allow, Forbid, or Replace.

Procedure

  1. Connect to your ACS cluster. See Obtain the kubeconfig file of a cluster and use kubectl to connect to the cluster or Use kubectl on Cloud Shell to manage ACS clusters.

  2. Create a file named cronjob.yaml with the following content:

    apiVersion: batch/v1
    kind: CronJob
    metadata:
      name: hello
    spec:
      schedule: "*/1 * * * *"
      jobTemplate:
        spec:
          template:
            spec:
              containers:
              - name: hello
                image: registry.cn-hangzhou.aliyuncs.com/acs/busybox:v1.29.2
                args:
                - /bin/sh
                - -c
                - date; echo Hello from the Kubernetes cluster
              restartPolicy: OnFailure
  3. Apply the manifest:

    kubectl create -f cronjob.yaml

    If the CronJob is created successfully, the output is:

    cronjob.batch/hello created

Verify the CronJob

A successful kubectl create confirms the CronJob resource exists, but does not mean a Job has run yet. Follow these steps to confirm the CronJob is scheduling Jobs as expected.

  1. Check the CronJob status:

    kubectl get cronjob hello

    The output is similar to:

    NAME    SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
    hello   */1 * * * *   False     0        <none>          10s

    The LAST SCHEDULE field shows <none> until the first scheduled run.

  2. Watch for a Job to be created (the schedule is every minute):

    kubectl get jobs --watch

    After about a minute, a Job appears:

    NAME             COMPLETIONS   DURATION   AGE
    hello-<id>       1/1           4s         1m
  3. Check the pod logs to confirm the Job ran successfully:

    kubectl logs -l job-name=hello-<id>

    The expected output includes the current date and a confirmation message:

    <current date and time>
    Hello from the Kubernetes cluster

What's next