上一篇 <<<Elastic-job的設計理念及原理說明
下一篇 >>>修改Elastic-Job默認session過期時間提升故障轉移速度
1.依賴包引入
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.kuhn-he/elastic-job-lite-spring-boot-starter -->
<dependency>
<groupId>com.github.kuhn-he</groupId>
<artifactId>elastic-job-lite-spring-boot-starter</artifactId>
<version>2.1.53</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.配置新增
#如果zookeeper集群的話,則以英文逗號隔開
elaticjob.zookeeper.server-lists=127.0.0.1:2181
elaticjob.zookeeper.namespace=my-project
3.代碼實現
@ElasticSimpleJob(cron = "0/5 * * * * ?",
jobName = "firstJob",
shardingTotalCount = 2,
jobParameter = "測試參數",
shardingItemParameters = "0=A,1=B")
@Component
public class MySimpleJob implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
System.out.println(String.format("------Thread ID: %s, 任務總片數: %s, " +
"當前分片項: %s,當前參數: %s," +
"當前任務名稱: %s,當前任務參數: %s," +
"當前任務的id: %s"
,
//獲取當前線程的id
Thread.currentThread().getId(),
//獲取任務總片數
shardingContext.getShardingTotalCount(),
//獲取當前分片項
shardingContext.getShardingItem(),
//獲取當前的參數
shardingContext.getShardingParameter(),
//獲取當前的任務名稱
shardingContext.getJobName(),
//獲取當前任務參數
shardingContext.getJobParameter(),
//獲取任務的id
shardingContext.getTaskId()
));
}
}
4.參數說明
配置任務的時候,這里定義了五個參數,分別是:
cron:cron表達式,用于控制作業觸發時間。
shardingTotalCount:作業分片總數
shardingItemParameters:分片序列號和參數用等號分隔,多個鍵值對用逗號分隔,分片序列號從0開始,不可大于或等于作業分片總數。如:0=a,1=b,2=c
jobParameters:作業自定義參數
description:作業描述
推薦閱讀:
<<<傳統任務調度實現方案及demo示例
<<<傳統任務調度存在的缺陷
<<<如何保證我們的定時任務只會觸發一次
<<<定時任務宕機后如何處理
<<<分布式任務調度平臺的特點
<<<XXL-Job和Elastic-job的區別
<<<Elastic-job的設計理念及原理說明
<<<修改Elastic-Job默認session過期時間提升故障轉移速度
<<<XXL-job入門介紹
<<<XXL-job的架構與執行邏輯說明
<<<XXL-Job Admin平臺搭建
<<<SpringBoot項目集成XXL-Job
<<<XXL-Job Admin任務調度的配置及預警示例
<<<XXL-Job使用分片集群機制將100W的短信在5min內發完
<<<XXL-Job如何搭建集群