<!-- configure scheduler -->
<!-- Set launcher properties -->
<bean id="pubLauncher" class="com.abc.PublicCompanyLauncher">
<!-- Job to execute -->
<property name="job" ref="publicCompanyJob" />
<!-- Job launcher defined in job repository -->
<property name="jobLauncher" ref="jobLauncher" />
</bean>
<!-- Scheduler definition -->
<task:scheduler id="pubScheduler" pool-size="3" />
<!-- Task definition to be scheduled -->
<task:scheduled-tasks scheduler="pubScheduler">
<!-- Scheduler will call method 'launch' every 10 seconds -->
<task:scheduled ref="pubLauncher" method="launch"
fixed-rate="10000" />
</task:scheduled-tasks>
2) Launcher class
package com.abcr;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
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 com.wealthx.uhnw.common.util.AppContext;
public class PublicCompanyLauncher {
private Job job;
private JobLauncher jobLauncher;
/**
* This method will be call every time after spring scheduler launch.
*/
public void launch() {
// Create parameters for job.
JobParameters jobParams = createJobParameters();
if (jobParams == null || jobParams.isEmpty()) {
System.out.println("nothing to do........................");
return;
}
// Run job.
JobExecution result;
try {
result = getJobLauncher().run(getJob(), jobParams);
} catch (JobExecutionAlreadyRunningException e) {
} catch (JobRestartException e) {
} catch (JobInstanceAlreadyCompleteException e) {
} catch (JobParametersInvalidException e) {
}
}
private JobParameters createJobParameters() {
// take only one .txt file in the folder to process
File dir = new File("d:/temp/test");
JobParameters jobParameters = null;
for (File f : dir.listFiles()) {
System.out.println("======================= " + f.getName());
if (!f.getName().endsWith(".txt"))
continue;
JobParameter jp = new JobParameter(f.getAbsolutePath());
Map<String, JobParameter> map = new HashMap<String, JobParameter>();
map.put("inputFile", jp);
jobParameters = new JobParameters(map);
break;
}
return jobParameters;
}
public void setJob(Job job) {
this.job = job;
}
public Job getJob() {
return job;
}
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
public JobLauncher getJobLauncher() {
return jobLauncher;
}
}
3) Main method
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"spring-context-jobs.xml");
context.start();
No comments:
Post a Comment