由于“只有返回无效的方法可以用”注释,当我使用配置而不是xml配置@Scheduled
时,如何使用Spring Batch和Spring Scheduler Task ?@Bean
您可以在下面找到我的完整配置文件。当我触发时它运行完美,main()
但只有一次。我想添加@Scheduled(fixedrate=9999)
以便以特定频率唤起相同的工作。据我所知,为了做到这一点,我应该@Scheduled
在 step1 方法周围添加,但我不能,因为它返回与 void 不同。
@Configuration
@EnableBatchProcessing
@EnableScheduling
public class BatchConfiguration {
private static final Logger log = LoggerFactory
.getLogger(BatchConfiguration.class);
@Bean
@StepScope
public FlatFileItemReader<Person> reader() {
log.info(new Date().toString());
FlatFileItemReader<Person> reader = new FlatFileItemReader<Person>();
reader.setResource(new ClassPathResource("test_person_json.js"));
reader.setLineMapper(new DefaultLineMapper<Person>() {
{
setLineTokenizer(new DelimitedLineTokenizer() {
{
setNames(new String[] {"firstName", "lastName" });
}
});
setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {
{
setTargetType(Person.class);
}
});
}
});
return reader;
}
@Bean
public ItemProcessor<Person, Person> processor() {
return new PersonItemProcessor();
}
@Bean
public ItemWriter<Person> writer(DataSource dataSource) {
JdbcBatchItemWriter<Person> writer = new JdbcBatchItemWriter<Person>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Person>());
writer.setSql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)");
writer.setDataSource(dataSource);
return writer;
}
@Bean
public Job importUserJob(JobBuilderFactory jobs, Step s1,
JobExecutionListener listener) {
return jobs.get("importUserJob").incrementer(new RunIdIncrementer())
.listener(listener).flow(s1).end().build();
}
@Bean
public Step step1(StepBuilderFactory stepBuilderFactory,
ItemReader<Person> reader, ItemWriter<Person> writer,
ItemProcessor<Person, Person> processor) {
return stepBuilderFactory.get("step1").<Person, Person> chunk(10)
.reader(reader).processor(processor).writer(writer).build();
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
//Question updated on Dec 3th 2015 with first suggestion
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class PersonScheduler {
private Job myImportJob;
private JobLauncher jobLauncher;
@Autowired
public PersonScheduler(JobLauncher jobLauncher, @Qualifier("myImportJob") Job myImportJob){
this.myImportJob = myImportJob;
this.jobLauncher = jobLauncher;
}
@Scheduled(fixedRate=9999)
public void runJob{
jobLauncher.run(myImportJob, new JobParameters());
}
}