Spring Boot Job Scheduler

时间:2017-12-01 11:40:44

标签: java spring spring-boot

我正在尝试在Spring Boot Batch Processing中定义多个作业。 我可以很容易地安排工作,但在我需要的时候遇到问题 只安排一些特定的工作。 这是我的方法,定义我安排工作的计划类。 我可以安排特定的工作,而不是一起安排所有工作吗? 感谢

import org.apache.log4j.Logger;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class JobScheduler {
static Logger logger=Logger.getLogger(JobScheduler.class);
@Autowired
JobLauncher jobLauncher;
@Autowired
private Job job;
   
@Scheduled(cron="10 * * * *  *") //Scheduling job at the interval of 10 seconds
public void scheduleJob(){
	JobParameters jobParameters=new JobParametersBuilder().addLong("time",System.currentTimeMillis()).toJobParameters();
	try {
		String jobName=job.getName();
		logger.info("JOB NAME===> "+jobName);
		JobExecution jobExecution=jobLauncher.run(job, jobParameters);
		logger.info("JOB'S STATUS===> "+jobExecution.getStatus());
		
	} catch (JobExecutionAlreadyRunningException e) {
	} catch (JobRestartException e) {
	} catch (JobInstanceAlreadyCompleteException e) {
	} catch (JobParametersInvalidException e) {
	}
}

}

2 个答案:

答案 0 :(得分:2)

是的,你可以这样做。创建一个单独的方法/类,并使用switch-case(使用java)实现它。对每个作业都有单独的方法调用(我假设您要安排不同的工作)。示例代码看起来像这样 -

switch(job) {
    case 'job1' {
    executejob1(job1, jobParameters);
    break;
    }
    case 'job2' {
    executejob1(job2, jobParameters);
    break;
    }
    case 'job3' {
    executejob1(job3, jobParameters);
    break;
    }
    case 'job4' {
    executejob1(job4, jobParameters);
    break;
    }
}

现在您只需要使用要与其作业参数一起安排的“作业”来调用它。希望这会有所帮助。

答案 1 :(得分:2)

看看这个简单的例子:

https://spring.io/guides/gs/scheduling-tasks/

您需要做的就是使用@SpringBootApplication启用计划 @EnableScheduling注释。

然后,您可以在要创建计划任务的任何@Component中为特定方法使用@Scheduled注释,并为每个任务设置不同的计划时间。 尽可能多的你想要的。

您无需创建JobScheduler,JobLuncher或Job。