如何在调度配置器中添加多个 spring 批处理作业?

How can I add multiple spring batch jobs inside the scheduling configurer?

因此下面的示例 java class 配置将从数据库动态获取 CRON 作业表达式。到目前为止,它仅适用于 1 个工作。但是,我有另一份工作并尝试通过调用 addTriggerTask 方法添加它,但由于此错误,工作失败。对我们如何触发多个作业有什么建议吗?

   ERROR: required a single bean, but 2 were found
    
   Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
@Configuration
@EnableScheduling
public class DynamicScheduler implements SchedulingConfigurer {

    private static Logger LOGGER = LoggerFactory.getLogger(DynamicScheduler.class);

    @Autowired
    ConfigRepo repo;

    @Autowired
    JobLauncher jobLauncher;

    @Autowired
    private Job job;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(() -> executeJob("job1"), t -> {
            CronTrigger crontrigger = new CronTrigger(repo.findById("cronExpressionJob1").get().getConfigValue());

            return crontrigger.nextExecutionTime(t);
        });

    }

    public void executeJob(String jobName) {        

        try {

            JobParameters jobParameters = new JobParametersBuilder()
                    .addString(jobName, String.valueOf(System.currentTimeMillis())).toJobParameters();

            jobLauncher.run(job, jobParameters);
        } catch (Exception e) {
            LOGGER.error("Failed due to exception thrown.", e);
        }

    }

}

在您当前的代码中,您正在使用 @AutowiredJob 注入 DynamicScheduler。当您只有一个工作时,这是明确的,但是一旦 添加另一个工作 Spring 就无法消除您想要注入哪个工作的歧义 .

这就是您看到错误的原因:

ERROR: required a single bean, but 2 were found

Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

如果您想处理多项工作,那么我建议从您的 class 中删除 @Autowired private Job job; 并使用 JobRegistry 按名称查找您的 Job局部变量。然后将 Job 及其 JobParameters 传递给 jobLauncher.run().

// get JobParameters for jobName
Job job = jobRegistry.getJob( jobName );
jobLauncher.run( job, jobParameters );