一、前序
如果你对elastic-job还不了解的话,建议你去看看我的《elastic-job分布式作业调度框架简介》,以下涉及到的参数配置请查看我的《elastic-job之Simple类型作业实现》
二、Script类型
Script类型作业意为脚本类型作业,支持shell,python,perl等所有类型脚本。只需通过控制台或代码配置scriptCommandLine即可,无需编码。执行脚本路径可包含参数,参数传递完毕后,作业框架会自动追加最后一个参数为作业运行时信息。
三、代码展示
package com.lwl.boot.job.script; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermissions; import com.dangdang.ddframe.job.config.JobCoreConfiguration; import com.dangdang.ddframe.job.config.script.ScriptJobConfiguration; import com.dangdang.ddframe.job.lite.api.JobScheduler; import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration; import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter; import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration; import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter; public class ApiJobScript { public static void main(String[] args) throws IOException { new JobScheduler(registryCenter(),configuration()).init(); } private static CoordinatorRegistryCenter registryCenter() { //配置zookeeper CoordinatorRegistryCenter registryCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration("localhost:2181", "elastic-job-demo")); registryCenter.init(); return registryCenter; } private static LiteJobConfiguration configuration() throws IOException { // 定义作业核心配置 JobCoreConfiguration coreConfig = JobCoreConfiguration.newBuilder("scriptElasticJob", "0/5 * * * * ?", 3).build(); ScriptJobConfiguration scriptJobConfig = new ScriptJobConfiguration(coreConfig, buildScriptCommandLine()); LiteJobConfiguration config = LiteJobConfiguration.newBuilder(scriptJobConfig).build(); return config; } private static String buildScriptCommandLine() throws IOException { //判断当前系统 if (System.getProperties().getProperty("os.name").contains("Windows")) { return Paths.get(ApiJobScript.class.getResource("/script/demo.bat").getPath().substring(1)).toString(); } Path result = Paths.get(ApiJobScript.class.getResource("/script/demo.sh").getPath()); Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x")); return result.toString(); } }
ScriptJobConfiguration主要参数:
coreConfig:作业核心配置
scriptCommandLine:脚本型作业执行命令行
demo.bat
demo.sh@echo Sharding Context: %*
#!/bin/bash echo Sharding Context: $*
四、启动
启动main方法查看控制台日志:代码已上传到服务器:github上:https://github.com/1181888200/boot-elastic-job