如何使Spring Schedulling定期调用单个tasklet的作业

时间:2016-01-18 20:29:54

标签: spring spring-batch spring-scheduled

使用注释@Scheduled(fixedRate = 600000),我希望每10分钟(600000毫秒= 600秒= 10分钟)触发作业,因此也可以触发tasklet。首先,我尝试使用return RepeatStatus.FINISHED因为我知道spring调度程序会触发每10分钟一个独立的线程。事实上,如果我使用return RepeatStatus.FINISHED,它会完成程序,换句话说,spring scheduler将不会再次调用该作业。 我不确定我是否在Spring Scheduler中设置了错误,或者我对于tasklet有一些错误的概念。根据经验,我的想法是基于我最近的研究,当我不需要读写器方法时,tasklet是一种可能的选择。我想创建一个批处理过程,只需每隔十分钟将文件从一个文件夹移动到另一个文件夹。没有文件处理。 从控制台日志中,我可以看到TestScheduller.runJob在我运行CommandLineJobRunner时被唤起了一次。 然后,作为我的第一次调查测试,我改为return RepeatStatus.CONTINUABLE,之后,我注意到tasklet确实运行了无限时间,但不是10分钟,让我们说每1秒钟。当然,这是不正确的。此外,这项工作根本没有完成。 所以,我的问题是:我怎样才能使spring.schedulling每十分钟唤起以下工作?

创建调度程序以便每10分钟触发一次tasklet:

@Component
public class TestScheduller {

       private Job job;
       private JobLauncher jobLauncher;

       @Autowired
       public TestScheduller(JobLauncher jobLauncher,
                     @Qualifier("helloWorldJob") Job job) {
              this.job = job;
              this.jobLauncher = jobLauncher;
       }

       @Scheduled(fixedRate = 600000) 
       public void runJob() {
              try {
                     System.out.println("runJob");
                     JobParameters jobParameters = new JobParametersBuilder().addLong(
                                  "time", System.currentTimeMillis()).toJobParameters();

                     jobLauncher.run(job, jobParameters);
              } catch (Exception ex) {
                     System.out.println("runJob exception ***********");
              }
       }

Java配置类

@Configuration
@ComponentScan("com.test.config")
@EnableScheduling
@Import(StandaloneInfrastructureConfiguration.class)
public class HelloWorldJobConfig {

       @Autowired
       private JobBuilderFactory jobBuilders;

       @Autowired
       private StepBuilderFactory stepBuilders;

       @Autowired
       private InfrastructureConfiguration infrastructureConfiguration;

       @Autowired
       private DataSource dataSource; // just for show...

       @Bean
       public Job helloWorldJob(){
              return jobBuilders.get("helloWorldJob")
                           .start(step())
                           .build();


       }

       @Bean
       public Step step(){
              return stepBuilders.get("step")
                           .tasklet(tasklet())
                           .build();
       }

       @Bean
       public Tasklet tasklet() {
              return new HelloWorldTasklet();
       }
}

微进程:     公共类HelloWorldTasklet实现Tasklet {

    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1)
            throws Exception {
        System.out.println("HelloWorldTasklet.execute called");
        return RepeatStatus.CONTINUABLE;
    }
}

控制台日志:

2016-01-18 14:16:16,376 INFO  org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@dcf3e99: startup date [Mon Jan 18 14:16:16 CST 2016]; root of context hierarchy
2016-01-18 14:16:16,985 WARN  org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.stepScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details
2016-01-18 14:16:17,024 WARN  org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method ScopeConfiguration.jobScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details
2016-01-18 14:16:17,091 INFO  org.springframework.context.support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerBySpringCGLIB$$e07fa052] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-18 14:16:17,257 INFO  org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory - Starting embedded database: url='jdbc:hsqldb:mem:testdb', username='sa'
2016-01-18 14:16:17,425 INFO  org.springframework.jdbc.datasource.init.ScriptUtils - Executing SQL script from class path resource [org/springframework/batch/core/schema-drop-hsqldb.sql]
2016-01-18 14:16:17,430 INFO  org.springframework.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [org/springframework/batch/core/schema-drop-hsqldb.sql] in 5 ms.
2016-01-18 14:16:17,430 INFO  org.springframework.jdbc.datasource.init.ScriptUtils - Executing SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql]
2016-01-18 14:16:17,456 INFO  org.springframework.jdbc.datasource.init.ScriptUtils - Executed SQL script from class path resource [org/springframework/batch/core/schema-hsqldb.sql] in 25 ms.
runJob
2016-01-18 14:16:18,083 INFO  org.springframework.batch.core.repository.support.JobRepositoryFactoryBean - No database type set, using meta data indicating: HSQL
2016-01-18 14:16:18,103 INFO  org.springframework.batch.core.repository.support.JobRepositoryFactoryBean - No database type set, using meta data indicating: HSQL
2016-01-18 14:16:18,448 INFO  org.springframework.batch.core.launch.support.SimpleJobLauncher - No TaskExecutor has been set, defaulting to synchronous executor.
2016-01-18 14:16:18,454 INFO  org.springframework.batch.core.launch.support.SimpleJobLauncher - No TaskExecutor has been set, defaulting to synchronous executor.
2016-01-18 14:16:18,558 INFO  org.springframework.batch.core.launch.support.SimpleJobLauncher - Job: [SimpleJob: [name=helloWorldJob]] launched with the following parameters: [{time=1453148177985}]
2016-01-18 14:16:18,591 INFO  org.springframework.batch.core.launch.support.SimpleJobLauncher - Job: [SimpleJob: [name=helloWorldJob]] launched with the following parameters: [{}]
2016-01-18 14:16:18,613 INFO  org.springframework.batch.core.job.SimpleStepHandler - Executing step: [step]
HelloWorldTasklet.execute called
2016-01-18 14:16:18,661 INFO  org.springframework.batch.core.launch.support.SimpleJobLauncher - Job: [SimpleJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
2016-01-18 14:16:18,661 INFO  org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@dcf3e99: startup date [Mon Jan 18 14:16:16 CST 2016]; root of context hierarchy
2016-01-18 14:16:18,665 INFO  org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory - Shutting down embedded database: url='jdbc:hsqldb:mem:testdb'
2016-01-18 14:16:18,844 INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
Picked up JAVA_TOOL_OPTIONS: -agentlib:jvmhook
Picked up _JAVA_OPTIONS: -Xrunjvmhook -Xbootclasspath/a:C:\PROGRA~2\HP\QUICKT~1\bin\JAVA_S~1\classes;C:\PROGRA~2\HP\QUICKT~1\bin\JAVA_S~1\classes\jasmine.jar

1 个答案:

答案 0 :(得分:0)

您需要调用TaskletStep的方法setAllowStartIfComplete(true)。 所以没有像

那样的方法
@Bean
public Step step(){
    TaskletStep step = stepBuilders.get("step")
                 .tasklet(tasklet())
                 .build();
    step.setAllowSta
}

应该看起来像:

{{1}}