前言
elastic-job 是当当开源的分布式定时作业框架,其基于 zookeeper 实现定时任务,上一篇文章中记录了一下使用 xml 文件配置定时作业。
随着 springboot 的兴起,现在大多数使用 java bean 的形式进行配置,同时还可能有些需求需要实现定时作业的动态生成。
demo 如下:
- 首先定义 elastic-job 配置类
ElasticJobConfig
@Configuration
public class ElasticJobConfig {
@Value("${elasticjob.zookeeper.list}")
private String serverlists;
@Value("${elasticjob.zookeeper.namespace}")
private String namespace;
/**
* zookeeper config
*
* @return
*/
@Bean
public ZookeeperConfiguration zkConfig() {
return new ZookeeperConfiguration(serverlists, namespace);
}
/**
* 初始化注册
*
* @param config
* @return
*/
@Bean(initMethod = "init")
public ZookeeperRegistryCenter regCenter(ZookeeperConfiguration config) {
return new ZookeeperRegistryCenter(config);
}
/**
* job 数据库存储配置;如果你要将作业信息配置到数据库中,可以在这里配置
*
* @return
*/
// @Bean
// public JobEventConfiguration jobEventConfiguration() {
// return new JobEventRdbConfiguration(null);
// }
@Bean
public ElasticJobListener elasticJobListener() {
return new MyElasticJobListener(100, 100);
}
}
- 定义一个 handler 来帮我们生成定时作业
因为是一个简单的 demo,所以我没有配置监听器,如果我们需要给不同的job,传递不用的参数,可以使用 jobParameter,然后在Job的 Context 中获取。
@Component
public class ElasticJobHandler {
@Resource
private ZookeeperRegistryCenter registryCenter;
// @Resource
// private JobEventConfiguration jobEventConfiguration;
@Resource
private MyElasticJobListener elasticJobListener;
private static LiteJobConfiguration.Builder simpleJobConfigBuilder(String jobName,
Class<? extends SimpleJob> jobClass, int shardingTotalCount, String cron, String id) {
return LiteJobConfiguration.newBuilder(new SimpleJobConfiguration(
JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount).jobParameter(id).build(),
jobClass.getCanonicalName()));
}
/**
* 添加一个定时任务
*
* @param jobName
* 任务名
* @param cron
* 表达式
* @param shardingTotalCount
* 分片数
*/
public void addJob(String jobName, String cron, Integer shardingTotalCount, String id) {
LiteJobConfiguration jobConfig = simpleJobConfigBuilder(jobName, MyJob.class, shardingTotalCount, cron, id)
.overwrite(true).build();
new JobScheduler(registryCenter, jobConfig, new ElasticJobListener[] {}).init();
}
}
- 定义一个 service 生成 job
@Service
public class ElasticJobService {
@Resource
private ElasticJobHandler jobHandler;
public void scanAddJob() {
for (int i = 0; i < 10; ++i) {
String jobName = "job_" + i;
String cron;
jobHandler.addJob(jobName, "0/5 * * * * ?", 1, String.valueOf(i));
}
}
}
- job
public class MyJob implements SimpleJob {
@Override
public void execute(ShardingContext shardingContext) {
System.out.println(shardingContext.toString());
}
}
- 启动类
@SpringBootApplication
public class Application implements CommandLineRunner {
@Resource
private ElasticJobService elasticJobService;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Override
public void run(String... args) throws Exception {
elasticJobService.scanAddJob();
}
}
运行结果:
2019-07-29 22:43:41.960 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'job_6' initialized from an externally provided properties instance.
2019-07-29 22:43:41.960 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.3.0
2019-07-29 22:43:42.043 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Scheduler job_6_$_NON_CLUSTERED started.
2019-07-29 22:43:42.062 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Using default implementation for ThreadExecutor
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.core.SchedulerSignalerImpl : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.3.0 created.
2019-07-29 22:43:42.063 INFO 11990 --- [ main] c.d.d.j.l.i.s.JobShutdownHookPlugin : Registering Quartz shutdown hook.
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.simpl.RAMJobStore : RAMJobStore initialized.
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'job_7' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 1 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler 'job_7' initialized from an externally provided properties instance.
2019-07-29 22:43:42.063 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Quartz scheduler version: 2.3.0
2019-07-29 22:43:42.163 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Scheduler job_7_$_NON_CLUSTERED started.
2019-07-29 22:43:42.180 INFO 11990 --- [ main] org.quartz.impl.StdSchedulerFactory : Using default implementation for ThreadExecutor
2019-07-29 22:43:42.181 INFO 11990 --- [ main] org.quartz.core.SchedulerSignalerImpl : Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
2019-07-29 22:43:42.181 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Quartz Scheduler v.2.3.0 created.
2019-07-29 22:43:42.181 INFO 11990 --- [ main] c.d.d.j.l.i.s.JobShutdownHookPlugin : Registering Quartz shutdown hook.
2019-07-29 22:43:42.181 INFO 11990 --- [ main] org.quartz.simpl.RAMJobStore : RAMJobStore initialized.
2019-07-29 22:43:42.181 INFO 11990 --- [ main] org.quartz.core.QuartzScheduler : Scheduler meta-data: Quartz Scheduler (v2.3.0) 'job_8' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 1 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
完成。