elastic job 动态设置定时任务

时间:2021-10-15 07:53:14

1. 版本

    <!-- import elastic-job lite core -->
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-core</artifactId>
<version>2.1.3</version>
</dependency>

<!-- import other module if need -->
<dependency>
<groupId>com.dangdang</groupId>
<artifactId>elastic-job-lite-spring</artifactId>
<version>2.1.3</version>
</dependency>

2. 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
xmlns:reg
="http://www.dangdang.com/schema/ddframe/reg"
xmlns:job
="http://www.dangdang.com/schema/ddframe/job"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.dangdang.com/schema/ddframe/reg
http://www.dangdang.com/schema/ddframe/reg/reg.xsd
http://www.dangdang.com/schema/ddframe/job
http://www.dangdang.com/schema/ddframe/job/job.xsd
"
>
<!--configure registry center -->
<reg:zookeeper id="regCenter" server-lists="${job.registry.address}" namespace="${job.namespace}" base-sleep-time-milliseconds="1000" max-sleep-time-milliseconds="3000" max-retries="3" />

<!--configure job -->
<!--<job:simple id="myElasticJob" class="com.zhuanche.util.MyElasticJob" registry-center-ref="regCenter" cron="0/10 * * * * ?" sharding-total-count="1" sharding-item-parameters="0=A" />-->
</beans>

3.1 代码

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.api.JobScheduler;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;

String cron
= DateUtil.getCron(activityEndTime);
logger.info(
"【定时任务执行的时间】cron={}",cron);
int shardingTotalCount = 1;
String jobName
= UUID.randomUUID().toString() + "-" + numprizeBaseId;
JobCoreConfiguration jobCoreConfiguration
= JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount).build();
SimpleJobConfiguration simpleJobConfiguration
= new SimpleJobConfiguration(jobCoreConfiguration, DynamicElasticJob.class.getCanonicalName());
JobScheduler jobScheduler
= new JobScheduler(zookeeperRegistryCenter, LiteJobConfiguration.newBuilder(simpleJobConfiguration).build());
try {
jobScheduler.init();
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("定时任务创建失败");
}

3.2 工具类

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* Created by admin on 2017/10/23.
*/
public class DateUtil {
private static final String CRON_DATE_FORMAT = "ss mm HH dd MM ? yyyy";

/***
*
@param date 时间
*
@return cron类型的日期
*/
public static String getCron(final Date date) {
SimpleDateFormat sdf
= new SimpleDateFormat(CRON_DATE_FORMAT);
String formatTimeStr
= "";
if (date != null) {
formatTimeStr
= sdf.format(date);
}
return formatTimeStr;
}
}