文档地址:http://elasticjob.io/docs/elastic-job-lite/00-overview/intro/
源码地址:https://github.com/elasticjob
源码解析:https://blog.youkuaiyun.com/spy19881201/article/details/61631799
一、Spring boot 整合
1. 添加依赖【在此只列出额外需要添加的elastic-job依赖的jar】
<!-- ElasticJobAutoConfiguration自动配置类作用-->
<dependency>
<groupId>com.github.kuhn-he</groupId>
<artifactId>elastic-job-lite-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
2. 添加相应配置项
elaticjob.zookeeper.server-lists=10.140.6.18:2181,10.140.6.19:2181 elaticjob.zookeeper.namespace=my-project
3. 创建定时任务
import com.dangdang.elasticjob.lite.annotation.ElasticSimpleJob; import org.springframework.stereotype.Component; import com.dangdang.ddframe.job.api.ShardingContext; (cron = "* * * * * ?", jobName = "test123", shardingTotalCount = 2, jobParameter = "测试参数", shardingItemParameters = "0=A,1=B") public class MySimpleJob implements com.dangdang.ddframe.job.api.simple.SimpleJob { public void execute(ShardingContext shardingContext) { System.out.println(String.format("------Thread ID: %s, 任务总片数: %s, " + "当前分片项: %s.当前参数: %s," + "当前任务名称: %s.当前任务参数: %s" , Thread.currentThread().getId(), shardingContext.getShardingTotalCount(), shardingContext.getShardingItem(), shardingContext.getShardingParameter(), shardingContext.getJobName(), shardingContext.getJobParameter() )); } }
4. 启动2个不同端口,查看执行结果
执行: java -jar xxx.jar --server.port=8081
------Thread ID: 83, 任务总片数: 2, 当前分片项: 0.当前参数: A,当前任务名称: com.willow.elasticJob.MySimpleJob.当前任务参数:
------Thread ID: 84, 任务总片数: 2, 当前分片项: 1.当前参数: B,当前任务名称: com.willow.elasticJob.MySimpleJob.当前任务参数:
------Thread ID: 89, 任务总片数: 2, 当前分片项: 0.当前参数: A,当前任务名称: com.willow.elasticJob.MySimpleJob.当前任务参数:
------Thread ID: 90, 任务总片数: 2, 当前分片项: 1.当前参数: B,当前任务名称: com.willow.elasticJob.MySimpleJob.当前任务参数: