Updated on 2024-11-21 GMT+08:00

Creating a CronJob

Scenario

A CronJob runs on a repeating schedule. You can perform time synchronization for all active nodes at a fixed time point.

Similar to Linux crontab, a CronJob runs periodically at the specified time and has the following characteristics:
  • A CronJob runs only once at the specified time.
  • A CronJob runs periodically at the specified time.

A CronJob is typically used to:

  • Schedule jobs at the specified time.
  • Create jobs to run periodically, for example, database backup and email sending.

Prerequisites

  • A cluster is available. For details about how to create a cluster, see Buying a CCE Autopilot Cluster.
  • VPC endpoints for accessing SWR and OBS have been configured. For details, see Configuring VPC Endpoints for Accessing SWR and OBS.
  • A Service of the LoadBalancer type has been created if the workload needs to be accessed by external networks.

    If a pod has multiple containers, the ports used by the containers cannot conflict with each other. If there is a conflict, the Deployment will fail to be created.

Using the CCE Console

  1. Log in to the CCE console.
  2. Click the cluster name to go to the cluster console, choose Workloads in the navigation pane on the left, and click the Create Workload in the upper right corner.
  3. Set basic information about the workload.

    Basic Info
    • Workload Type: Select CronJob.
    • Workload Name: Enter a name for the workload. Enter 1 to 63 characters starting with a lowercase letter and ending with a lowercase letter or digit. Only lowercase letters, digits, and hyphens (-) are allowed.
    • Namespace: Select a namespace. The default value is default. You can also click Create Namespace to create one. For details, see Creating a Namespace.
    Container Settings
    • Container Information
      A pod can have more than one container. You can click Add Container on the right to configure multiple containers.
      • Basic Info: Configure basic information about each container.

        Parameter

        Description

        Container Name

        Enter a name for the container.

        Pull Policy

        Image update or pull policy. If you select Always, the image is pulled from the image repository each time. If you do not select Always, the existing image of the node is preferentially used. If the image does not exist, the image is pulled from the image repository.

        Image Name

        Click Select Image and select the image used by the container.

        To use a third-party image, see Using Third-Party Images.

        Image Tag

        Select the image tag to be deployed.

        CPU Quota

        CPU limit, which is the maximum CPU available for the container to prevent excessive resource usage.

        Memory Quota

        Memory limit, which is the maximum memory available for the container. When the container's memory usage exceeds the memory limit, the container will be terminated.

        (Optional) Init Container

        Whether the container will be used as an init container. An init container does not support health check.

        An init container is a special container that runs before other app containers in a pod are started. Each pod can contain multiple containers. In addition, a pod can contain one or more init containers. Application containers in a pod are started and run only after the running of all init containers completes. For details, see Init Containers.

      • (Optional) Lifecycle: Configure operations to be performed in a specific phase of the container lifecycle, such as Startup Command, Post-Start, and Pre-Stop. For details, see Configuring the Container Lifecycle.
      • (Optional) Environment Variables: Configure variables for the container running environment using key-value pairs. These variables transfer external information to containers running in pods and can be flexibly modified after application deployment. For details, see Configuring Environment Variables.
    • Image Access Credential: Select the credential used for accessing the image repository. The default value is default-secret. You can use default-secret to access images in SWR. For details about default-secret, see default-secret.

    Schedule

    • Concurrency Policy: There are three options:
      • Forbid: A new job cannot be created before the previous job is completed.
      • Allow: The CronJob allows concurrently running jobs, which preempt cluster resources.
      • Replace: A new job replaces the previous job when it is time to create a job but the previous job is not completed.
    • Policy Settings: Specify when a new job is executed. Policy settings in YAML are implemented using cron expressions.
      • A job is executed at a fixed interval. The unit can be minute, hour, day, or month. For example, if a job is executed every 30 minutes and the corresponding cron expression is */30 * * * *, the execution time starts from 0 in the unit range, for example, 00:00:00, 00:30:00, 01:00:00, and ....
      • A job is executed by month. For example, if a job is executed at 00:00 on the first day of each month, the cron expression is 0 0 1 */1 *, and the execution time is ****-01-01 00:00:00, ****-02-01 00:00:00, and ....
      • A job is executed by week. For example, if a job is executed at 00:00 every Monday, the cron expression is 0 0 * * 1, and the execution time is ****-**-01 00:00:00 on Monday, ****-**-08 00:00:00 on Monday, and ....
      • Custom Cron Expression: For details about how to use cron expressions, see CronJob.
      • If a job is executed at a fixed time (by month) and the date in a month does not exist, the job will not be executed in this month. For example, the execution will skip February if the date is set to 30.
      • Due to the definition of cron, the fixed period is not a strict period. The time unit range is divided from 0 by period. For example, if the unit is minute, the value ranges from 0 to 59. If the value cannot be exactly divided, the last period is reset. Therefore, an accurate period can be represented only when the period can be evenly divided.

        Take a job that is executed by hour as an example. As /2, /3, /4, /6, /8, and /12 can exactly divide 24 hours, an accurate period can be represented. If another period is used, the last period will be reset at the beginning of a new day. For example, if the cron expression is * */12 * * *, the execution time is 00:00:00 and 12:00:00 every day. If the cron expression is * */13 * * *, the execution time is 00:00:00 and 13:00:00 every day. At 00:00 on the next day, the execution time is updated even if the period does not reach 13 hours.

    • Job Records: You can set the number of jobs that are successfully executed or fail to be executed. If the values are set to 0, none of the jobs will be kept after they finish.
    (Optional) Advanced Settings
    • Labels and Annotations: Add labels or annotations for pods using key-value pairs. After entering the key and value, click Confirm. For details about how to use and configure labels and annotations, see Configuring Labels and Annotations.

  4. Click Create Workload in the lower right corner.

Using kubectl

Node affinity and anti-affinity are not available for CCE Autopilot clusters. When you use kubectl to create a workload, do not configure the affinity field to prevent pod creation failures.

A CronJob has the following configuration parameters:

  • .spec.schedule: takes a Cron format string, for example, 0 * * * * or @hourly, as schedule time of jobs to be created and executed.
  • .spec.jobTemplate: specifies jobs to be run and has the same schema as when you are Creating a Job Using kubectl.
  • .spec.startingDeadlineSeconds: specifies the deadline for starting a job.
  • .spec.concurrencyPolicy: specifies how to treat concurrent executions of a job created by the CronJob. The following options are supported:
    • Allow (default value): allows concurrently running jobs.
    • Forbid: forbids concurrent runs, skipping next run if previous has not finished yet.
    • Replace: cancels the currently running job and replaces it with a new one.

The following is an example CronJob, which is saved in the cronjob.yaml file.

In clusters of v1.21 or later, the apiVersion value of CronJobs is batch/v1.

In clusters earlier than v1.21, the apiVersion value of CronJobs is batch/v1beta1.

apiVersion: batch/v1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            command:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure
          imagePullSecrets:
            - name: default-secret

Run the job.

  1. Create a CronJob.

    kubectl create -f cronjob.yaml

    Information similar to the following is displayed:

    cronjob.batch/hello created

  2. Query the running status of a CronJob.

    kubectl get cronjob

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

    kubectl get jobs

    NAME               COMPLETIONS   DURATION   AGE
    hello-1597387980   1/1           27s        45s

    kubectl get pod

    NAME                           READY     STATUS      RESTARTS   AGE
    hello-1597387980-tjv8f         0/1       Completed   0          114s
    hello-1597388040-lckg9         0/1       Completed   0          39s

    kubectl logs hello-1597387980-tjv8f

    Fri Aug 14 06:56:31 UTC 2020
    Hello from the Kubernetes cluster

    kubectl delete cronjob hello

    cronjob.batch "hello" deleted

    If a CronJob is deleted, the related jobs and pods are deleted accordingly.

Related Operations

After a CronJob is created, you can perform operations described in Table 1.

Table 1 Other operations

Operation

Description

Editing a YAML file

Click More > Edit YAML next to the CronJob name to edit the YAML file of the current job.

Stopping a CronJob

  1. Select the CronJob to be stopped and click Stop in the Operation column.
  2. Click Yes.

Deleting a CronJob

  1. Select the CronJob to be deleted and click More > Delete in the Operation column.
  2. Click Yes.

    Deleted CronJobs cannot be recovered.