返回

从头到尾:轻松上手SpringBoot整合阿里云SchedulerX分布式任务调度组件

前端

一、SchedulerX简介

阿里云SchedulerX是一个分布式任务调度组件,能够帮助您轻松管理和调度任务。它支持多种任务类型,包括Java任务、Python任务、Shell任务等,并提供了丰富的调度策略,如Cron表达式、任务组、任务依赖等。SchedulerX还可以进行任务监控和告警,帮助您及时发现并处理任务问题。

二、SchedulerX集成SpringBoot

  1. 添加依赖

在你的SpringBoot项目的pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.aliyun.schedulerx</groupId>
    <artifactId>schedulerx-starter</artifactId>
    <version>2.0.3</version>
</dependency>
  1. 创建任务类
import com.aliyun.schedulerx.spring.boot.annotation.ElasticJobConfig;
import org.springframework.stereotype.Component;

@Component
@ElasticJobConfig(
        cron = "0/5 * * * * ?",
        description = "测试任务",
        shardingTotalCount = 1
)
public class MyTask implements ElasticJob {

    @Override
    public void execute(ShardingContext context) {
        System.out.println(String.format("当前时间:%s,分片总数:%s,分片项:%s",
                new Date(),
                context.getShardingTotalCount(),
                context.getShardingItem()));
    }
}
  1. 注册任务

在你的SpringBoot项目中创建一个类,继承自ElasticJobRegistrar,并重写registerElasticJobs方法来注册任务。

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.elasticjob.lite.api.JobScheduler;
import com.dangdang.elasticjob.lite.config.LiteJobConfiguration;
import com.dangdang.elasticjob.lite.spring.api.SpringJobScheduler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class ElasticJobConfig extends ElasticJobRegistrar {

    @Value("${schedulerx.server.address}")
    private String serverAddress;

    @Value("${schedulerx.namespace}")
    private String namespace;

    @PostConstruct
    public void init() {
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverAddress, namespace);

        LiteJobConfiguration liteJobConfiguration = LiteJobConfiguration.newBuilder(MyTask.class.getSimpleName())
                .cron("0/5 * * * * ?")
                .shardingTotalCount(1)
                .build();

        JobScheduler jobScheduler = new SpringJobScheduler(zookeeperConfiguration, liteJobConfiguration, applicationContext);
        jobScheduler.init();
    }

    @Override
    public void registerElasticJobs(ElasticJobListener elasticJobListener) {
        // do nothing
    }
}
  1. 启动任务调度器

在你的SpringBoot项目的main方法中启动任务调度器。

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

三、SchedulerX使用指南

  1. 创建命名空间

在SchedulerX控制台创建一个命名空间。

  1. 创建任务

在SchedulerX控制台创建任务,并选择相应的任务类型。

  1. 配置任务参数

设置任务的Cron表达式、任务组、任务依赖等参数。

  1. 启动任务

启动任务后,任务将按照设定的时间执行。

  1. 监控任务

SchedulerX提供了任务监控和告警功能,您可以实时查看任务的执行状态,并及时发现并处理任务问题。

四、结语

SchedulerX是一个功能强大、易于使用的分布式任务调度组件。通过将SchedulerX整合到你的SpringBoot项目中,您可以轻松管理和调度任务,提高任务执行效率。