Elastic-job之脚本作业

脚本作业是用来定时调度脚本文件的,如windows的cmd,linux上的shell文件,在调度的时候会把当前调度的ShardingContext的转化为一个JSON串作为脚本调度的参数进行传递。其不需要指定作业对应的class,因为我们不是通过我们自己的class来进行调度的。脚本作业在配置时由<job:script/>配置,示例如下:

<job:script id="myScriptJob" registry-center-ref="regCenter"
	cron="0/30 * * * * ?" sharding-total-count="3"
	sharding-item-parameters="0=shard-0,1=shard-1,2=shard-2"
	script-command-line="echo hello" overwrite="true"/>

其中script-command-line属性用于指定该调度对应的脚本文件路径或某个可执行的指令。这里只是简单的打印一下hello和ShardingContext对应的JSON形式。其它配置参数和之前介绍的简单作业的配置参数类似。

脚本作业将由com.dangdang.ddframe.job.executor.type.ScriptJobExecutor执行。其代码如下:

public final class ScriptJobExecutor extends AbstractElasticJobExecutor {
    
    public ScriptJobExecutor(final JobFacade jobFacade) {
        super(jobFacade);
    }
    
    @Override
    protected void process(final ShardingContext shardingContext) {
        final String scriptCommandLine = ((ScriptJobConfiguration) getJobRootConfig().getTypeConfig()).getScriptCommandLine();
        if (Strings.isNullOrEmpty(scriptCommandLine)) {
            throw new JobConfigurationException("Cannot find script command line for job '%s', job is not executed.", shardingContext.getJobName());
        }
        executeScript(shardingContext, scriptCommandLine);
    }
    
    private void executeScript(final ShardingContext shardingContext, final String scriptCommandLine) {
        CommandLine commandLine = CommandLine.parse(scriptCommandLine);
        commandLine.addArgument(GsonFactory.getGson().toJson(shardingContext), false);
        try {
            new DefaultExecutor().execute(commandLine);
        } catch (final IOException ex) {
            throw new JobConfigurationException("Execute script failure.", ex);
        }
    }
}

(本文由Elim写于2017年10月1日)

猜你喜欢

转载自elim.iteye.com/blog/2407290