Как сделать Spring Schedulling, чтобы периодически вызывать работу с одним тасклетом

С аннотацией @Scheduled(fixedRate = 600000)Я ожидал запуска задания и, следовательно, тасклета каждые 10 минут (600000 миллисекунд = 600 секунд = 10 минут). Во-первых, я попытался с помощью return RepeatStatus.FINISHED поскольку я понял, что планировщик пружины будет запускать каждые 10 минут независимую нить. На самом деле, если я использую return RepeatStatus.FINISHED, он завершает программу вообще, другими словами, планировщик Spring больше не будет вызывать задание. Я не уверен, что я настроил что-то не так в Spring Scheduler, или у меня возникло неправильное представление о тасклете. Как правило, я думаю о том, что я недавно изучал, когда мне не нужен метод чтения и записи, тасклет является возможной альтернативой. Я хочу создать пакетный процесс, который будет просто перемещать файл из одной папки в другую папку каждые десять минут. Там не будет никакого файлового процесса. Из журналов консоли я вижу, что TestScheduller.runJob был вызван однажды, когда я побежал CommandLineJobRunner, Затем, как мой первый исследовательский тест, я изменил на return RepeatStatus.CONTINUABLE и после этого я заметил, что тасклет работал бесконечно долго, но вместо 10 минут, скажем, каждую 1 секунду. Конечно, это не правильно. Кроме того, работа не закончилась вообще. Итак, мой вопрос: как я могу заставить spring.schedulling вызывать следующую работу каждые десять минут?

Планировщик создан для запуска тасклета каждые 10 минут:

@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 реализует Тасклет {

    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 ответ

Вам нужно вызвать метод setAllowStartIfComplete(true) из TaskletStep. Таким образом, вместо того, чтобы метод, как

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

это должно выглядеть так:

@Bean
public Step step(){
    TaskletStep step = stepBuilders.get("step")
                 .tasklet(tasklet())
                 .build();
    step.setAllowSta
}
Другие вопросы по тегам