引入 Maven 依赖

  1. <dependency>
  2. <groupId>org.apache.shardingsphere.elasticjob</groupId>
  3. <artifactId>elasticjob-lite-core</artifactId>
  4. <version>${latest.release.version}</version>
  5. </dependency>

作业开发

  1. public class MyJob 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. JobConfiguration jobConfig = JobConfiguration.newBuilder("MyJob", 3).cron("0/5 * * * * ?").build();

作业调度

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