All Products
Search
Document Center

SchedulerX:Spring jobs

Last Updated:Jun 28, 2024

Scheduled Spring jobs facilitate the application of scheduled jobs in a Java system but also have many limits in enterprise scenarios. Spring jobs that are managed by SchedulerX can meet more requirements in enterprise scenarios.

Prerequisites

Connection description

Step 1: Add a dependency to the pom.xml file

Add a dependency and a main class to the pom.xml file of the application. In this example, a Spring Boot application is used.

Replace schedulerx2.version with the latest version of the SchedulerX agent. For more information, see Agent release notes.

<dependency>
  <groupId>com.aliyun.schedulerx</groupId>
  <artifactId>schedulerx2-spring-boot-starter</artifactId>
  <version>${schedulerx2.version}</version>
  <!-- If you use Logback, you must exclude Log4j and Log4j2. -->
  <exclusions>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
    </exclusion>
    <exclusion>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Regardless of whether you use scheduled Spring jobs for the first time, keep the @EnableScheduling annotation enabled in the main class. Sample code:

@SpringBootApplication
@EnableScheduling /**Enable scheduled Spring jobs.*/
public class SchedulerXWorkerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SchedulerXWorkerApplication.class, args);
    }
}

/** Native scheduled Spring job class*/
@Service
public class SpringScheduledProcessor {
    @Scheduled(cron = "0/2 * * * * ?")
    public void hello() {
        logger.info(DateUtil.now() + " hello world. start");
        logger.info(DateUtil.now() + " hello world. end");
    }
}

If you use the preceding configurations for the first time or have used the preceding configurations, SchedulerX does not take over the existing scheduled Spring jobs in the application by default. These jobs are still scheduled by the Spring container, and the execution of these jobs is not affected.

Step 2: Add parameter configuration

To allow SchedulerX to take over scheduled Spring jobs, you can add the following configuration to the Properties file.

# 1. Configure application access.
spring.schedulerx2.endpoint=${endpoint}
spring.schedulerx2.namespace=${namespace}
spring.schedulerx2.groupId=${groupId}
spring.schedulerx2.appKey=${appKey}

# 2. Enable SchedulerX to take over scheduled Spring jobs.
spring.schedulerx2.task.scheduling.scheduler=schedulerx

# 3. After you allow SchedulerX to take over scheduled Spring jobs, you can enable automatic job synchronization. The following parameters are optional.
#spring.schedulerx2.task.scheduling.sync=true
# spring.schedulerx2.regionId=The ID of the region to which you want to synchronize the jobs (For more information about region IDs, see Endpoints.)
#spring.schedulerx2.aliyunAccessKey=XXXXXXXXX
#spring.schedulerx2.aliyunSecretKey=XXXXXXXXX

Configuration instruction:

  • Configure application access: Log on to the SchedulerX console. In the left-side navigation pane, click Application Management. On the Application Management page, find the application that you want to manage and click Access configuration in the Operation column to view the access configuration information. The first time you connect Spring jobs to SchedulerX, you must create an application for the jobs.

  • Enable automatic synchronization of existing jobs: If you have already used scheduled Spring jobs and have a large number of existing scheduled jobs, you can enable automatic synchronization of jobs in the application configuration file. This frees you from the manual job creation operations described in Step 3. For more information about region IDs, see Endpoints.

Important

To guarantee that an auto-synchronized job adheres to the identical execution pattern as native Spring jobs in a cluster, the system defaults the Execution mode parameter to Broadcast run. This configuration ensures that each worker node in the cluster runs the job simultaneously at the specified point in time. If the job needs to be run on a specified worker node in the cluster, you can directly set the Execution mode parameter for the job to Stand-alone operation in the SchedulerX console. For more information about the parameters, see Step 3.

Step 3: (Optional) Manually create a scheduled job

Note

If you enable automatic job synchronization in Step 2, you do not need to manually create a scheduled job.

  1. Log on to the SchedulerX console.

  2. In the left-side navigation pane, click Task Management.

  3. On the Task Management page, click Create task. Set Task type to SpringSchedule, and configure a class name and a method name.

    Parameter

    Description

    Task name

    The name of the job that you want to create.

    Description

    The description of the job. Specify a concise and clear description to facilitate job search and management.

    Application ID

    The group to which the job belongs. Select a value from the drop-down list.

    Task type

    The programming language that you want to use to create the job. Valid values include Java, Shell, Python, Golang, Http, Node.js, XXL-JOB, and DataWorks. When you select Shell, Python, or Golang, an editor is displayed. You can enter a script in the editor.

    In this example, this parameter is set to SpringSchedule.

    spring scheduleConfiguration

    The complete class name and method name of the job.

    Execution mode

    The mode in which the job is run. The following execution modes are supported:

    • Stand-alone operation: The job is run on a random worker.

    • Broadcast run: The job is concurrently run on all workers, and the system waits until all workers complete the job.

    Note

    The parameters in the Advanced Configuration section vary based on the selected execution mode.

    Priority

    If multiple jobs of the same application run on the same worker at the same time, jobs with high priorities are run first. However, if multiple jobs of the same application run on multiple workers, jobs with different priorities are scheduled to different workers. In this case, jobs with low priorities may be run first. SchedulerX uses preemptible queues to avoid this issue and ensure that a job with a higher priority in a queue is triggered first. For more information, see Preemptible queues.

    Task parameters

    A random string that can be obtained from the context when SchedulerX runs the job.

  4. Configure the trigger frequency.

    Note

    The frequency that is specified in the SchedulerX console prevails, and the configuration of the native annotation @Scheduled in the code of the scheduled Spring job becomes invalid. However, the annotation is retained in the code.

    The following table describes the parameters.

    Parameter

    Description

    Time type

    • none: The job is triggered by using a workflow.

    • cron: The job is scheduled based on a cron expression.

    • api: The job is triggered by calling an API operation.

    • fixed_rate: The job is triggered at a specified interval.

    • second_delay: The job is triggered with a delay from 1 to 60 seconds.

    • one_time: The job is triggered only once at the specified point in time.

    cron expression

    The cron expression based on which the job is scheduled. You can manually enter a cron expression based on the cron syntax. You can also use the tool provided by SchedulerX to automatically generate a valid cron expression.

    Fixed frequency

    The interval at which the job is triggered. This parameter is available only if the Task type parameter is set to fixed_rate. The value must be greater than 60. Unit: seconds. For example, a value of 200 indicates that the job is triggered at an interval of 200 seconds.

    Fixed delay

    The fixed delay. This parameter is available only if the Task type parameter is set to second_delay. Valid values: 1 to 60. Unit: seconds. For example, the value 5 indicates that the job is triggered with a delay of 5 seconds.

    The following table describes the advanced timing configurations.

    Parameter

    Description

    Time offset

    Specify the offset between the timestamp of the data to be processed and the time when the job is triggered. You can obtain the offset value from the context when SchedulerX runs the job.

    Time zone

    Select the time zone of a country or region or select a GMT time zone based on your business requirements.

    Calendar

    Select Workday or Financial day.

  5. Configure alert conditions and notification methods. For more information about the notification methods, see Notification contacts and notification contact groups.

    After you complete the configurations, SchedulerX can run scheduled Spring jobs. The console also provides native Spring jobs with enterprise-level O&M capabilities, including visualized management and control, job log query, execution chain view, and job execution notification and alerting.

Step 4: Verify application access

  1. Start the Spring application. Log on to the SchedulerX console. In the left-side navigation pane, click Application Management. On the Application Management page, check the value in the Total number of instances column for the application. If the value is greater than 0, the application is connected to SchedulerX.

image

  1. In the left-side navigation pane, click Task Management. On the page that appears, find the job that corresponds to the application and click Run once in the Operation column. The configurations take effect if the job is successfully run.

FAQ

Why does the original Spring timer still run after SchedulerX takes over scheduled Spring jobs?

If a custom scheduler is specified in your application, SchedulerX overwrites the custom scheduler. Check whether the class that implements the org.springframework.scheduling.annotation.SchedulingConfigurer interface exists in the application project and whether the setScheduler method of ScheduledTaskRegistrar is called to overwrite the default scheduler. If the class exists or the method is called, comment out the related code.

How do I obtain the context for a Spring job?

Add the following code to your application project code to obtain the context:

JobContext jobContext = ContainerFactory.getContainerPool().getContext();

Does a Spring job return a processing result?

When the version of your client is later than 1.10.11, Spring jobs can return processing results. The processing results are returned based on the specified scheduling methods.

@Scheduled(cron = "0/5 * * * * ?")
public ProcessResult helloStandalone1() {
    try {
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. start");
        TimeUnit.SECONDS.sleep(2L);
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. end");
    } catch (Exception e) {
        e.printStackTrace();
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. exception end..");
    }
    return new ProcessResult(true, "Processing result");
}

@Scheduled(cron = "0/5 * * * * ?")
public String helloStandalone2() {
    try {
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. start");
        TimeUnit.SECONDS.sleep(2L);
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. end");
    } catch (Exception e) {
        e.printStackTrace();
        logger.info(DateUtil.now() + " " + Thread.currentThread().getName() + " hello world. exception end..");
    }
    return "Processing result";
}