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
Log on to the ACS console. In the left-side navigation pane, click Clusters.
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.
On the CronJobs page, click Create from Image in the upper-right corner.
On the Basic Information wizard page, configure the following settings.
Parameter Description Name Enter a name for the CronJob. Type Select CronJob. Label Add labels to identify the application. Annotations Add annotations to the application. Instance Type Select the instance type. For details, see ACS pod overview. QoS Type Select a QoS class. General-purpose pods support Default and BestEffort; performance-enhanced pods support Default only. For details, see Computing power QoS. 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.
In the General section, configure the basic container settings.
Parameter Description Image Name Select 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 Policy Controls 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 secret Click 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 Resources Set 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 Parameter Optional. 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 Containers Optional. 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. Optional: In the Ports section, click Add to expose container ports.
Parameter Description Name Enter a name for the port. Container Port Specify a port number (1–65535). Protocol Select TCP or UDP. 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.
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.
Parameter Description HTTP Sends an HTTP GET request. Configure the protocol (HTTP or HTTPS), path, port (1–65535), and optional custom headers. TCP Attempts to open a TCP socket on the specified port. The container is considered healthy if the connection succeeds. Command Runs 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 Threshold Consecutive successes required to mark the container healthy. Default: 1. For liveness probes, this must be 1. Unhealthy Threshold Consecutive failures required to mark the container unhealthy. Default: 3. Minimum: 1. Optional: In the Lifecycle section, configure container lifecycle hooks. For more information, see Attach handlers to container lifecycle events.
Parameter Description Start Command that runs before the container starts. Post Start Command that runs after the container starts. Pre Stop Command that runs before the container terminates. 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.
Optional: In the Log section, configure log collection.
Parameter Description Logstore Create a Logstore in Log Service to store collected logs. Log Path in Container Specify stdoutto collect standard output, or enter a file path (wildcards supported, for example,/var/log/nginx).Custom Tag Add tags to logs on collection, for filtering and analysis. Click Next.
Step 3: Configure advanced settings
In theCronJob Settings section, configure the schedule and concurrency behavior.
Parameter Description Schedule Set when the CronJob runs—hourly, daily, weekly, monthly, or a custom cron expression. See the cron expression reference below. Concurrency Policy Controls 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 History Number of completed and failed Jobs to retain. Set to 0to 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 * * 1runs every Monday at 09:00. For the full syntax, see Cron expressions.In the Job Settings section, configure the Job execution parameters.
Parameter Default Description Completions 1 Number of pods that must complete successfully for the Job to be considered done. Parallelism 1 Maximum number of pods running in parallel at any time. Timeout — Time limit for the Job ( activeDeadlineSeconds). If the Job does not finish within this duration, the system attempts to terminate it.BackoffLimit 6 Maximum number of retry attempts when pods fail. Failed pods are recreated with an exponential back-off delay, capped at 6 minutes. Restart — Restart policy for containers: Never or On Failure. Tip: To set how late a Job can start after its scheduled time, use
startingDeadlineSecondsin your YAML (this parameter is not available in the console). For example, if a backup Job runs twice a day and you setstartingDeadlineSeconds: 28800, the Job can start up to 8 hours late—any later, and it waits for the next scheduled run.Optional: In the Labels,Annotations section, click Add to add labels and annotations to the pod.
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
| Parameter | Description |
|---|---|
.spec.schedule | Cron expression defining when the Job runs. See Cron schedule syntax. |
.spec.jobTemplate | Defines the Job to run. See Job patterns. |
.spec.startingDeadlineSeconds | How many seconds past the scheduled time the Job is still allowed to start. |
.spec.concurrencyPolicy | Concurrency behavior: Allow, Forbid, or Replace. |
Procedure
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.
Create a file named
cronjob.yamlwith 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: OnFailureApply the manifest:
kubectl create -f cronjob.yamlIf 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.
Check the CronJob status:
kubectl get cronjob helloThe output is similar to:
NAME SCHEDULE SUSPEND ACTIVE LAST SCHEDULE AGE hello */1 * * * * False 0 <none> 10sThe
LAST SCHEDULEfield shows<none>until the first scheduled run.Watch for a Job to be created (the schedule is every minute):
kubectl get jobs --watchAfter about a minute, a Job appears:
NAME COMPLETIONS DURATION AGE hello-<id> 1/1 4s 1mCheck 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