快速入门

1. 使用API配置启动

引入maven依赖

  1. <dependency>
  2. <groupId>io.elasticjob</groupId>
  3. <artifactId>elastic-job-lite-core</artifactId>
  4. <version>${latest.release.version}</version>
  5. </dependency>

作业开发

  1. public class MyElasticJob implements SimpleJob {
  2. @Override
  3. public void execute(ShardingContext context) {
  4. switch (context.getShardingItem()) {
  5. case 0:
  6. // do something by sharding item 0
  7. break;
  8. case 1:
  9. // do something by sharding item 1
  10. break;
  11. case 2:
  12. // do something by sharding item 2
  13. break;
  14. // case n: ...
  15. }
  16. }
  17. }

作业配置

  1. // 定义作业核心配置
  2. JobCoreConfiguration simpleCoreConfig = JobCoreConfiguration.newBuilder("demoSimpleJob", "0/15 * * * * ?", 10).build();
  3. // 定义SIMPLE类型配置
  4. SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(simpleCoreConfig, SimpleDemoJob.class.getCanonicalName());
  5. // 定义Lite作业根配置
  6. LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).build();

启动作业

  1. public class JobDemo {
  2. public static void main(String[] args) {
  3. new JobScheduler(createRegistryCenter(), createJobConfiguration()).init();
  4. }
  5. private static CoordinatorRegistryCenter createRegistryCenter() {
  6. CoordinatorRegistryCenter regCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration("zk_host:2181", "elastic-job-demo"));
  7. regCenter.init();
  8. return regCenter;
  9. }
  10. private static LiteJobConfiguration createJobConfiguration() {
  11. // 创建作业配置
  12. // ...
  13. }
  14. }

2. 使用Spring配置启动

  1. <dependency>
  2. <groupId>io.elasticjob</groupId>
  3. <artifactId>elastic-job-lite-spring</artifactId>
  4. <version>${latest.release.version}</version>
  5. </dependency>

作业开发

同使用API配置中作业开发

作业配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:reg="http://www.dangdang.com/schema/ddframe/reg"
  5. xmlns:job="http://www.dangdang.com/schema/ddframe/job"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.dangdang.com/schema/ddframe/reg
  9. http://www.dangdang.com/schema/ddframe/reg/reg.xsd
  10. http://www.dangdang.com/schema/ddframe/job
  11. http://www.dangdang.com/schema/ddframe/job/job.xsd
  12. ">
  13. <!--配置作业注册中心 -->
  14. <reg:zookeeper id="regCenter" server-lists="yourhost:2181" namespace="dd-job" base-sleep-time-milliseconds="1000" max-sleep-time-milliseconds="3000" max-retries="3" />
  15. <!-- 配置作业-->
  16. <job:simple id="demoSimpleSpringJob" class="xxx.MyElasticJob" registry-center-ref="regCenter" cron="0/10 * * * * ?" sharding-total-count="3" sharding-item-parameters="0=A,1=B,2=C" />
  17. </beans>

启动作业

将配置Spring命名空间的xml通过Spring启动,作业将自动加载。

详细的规则配置请参考配置手册