Vadim
Vadim

Reputation: 557

start scheduler with spring annotation in method

I want to add spring annotation @Scheduled to spring bean and start task in method in another class. There is only one way to start task in spring reference - Scheduling-Tasks by @EnableScheduling. How to start it without @SpringBootApplication and spring boot runner.

@Component
public class ScheduledTasks {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now {}" + dateFormat.format(new Date()));
    }
}

@SpringBootApplication
@EnableScheduling
public class SpringSheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSheduleApplication.class, args);
    }
}

@Component
    public class ShedullerStarter {
        public void start(){
            ScheduledTasks tasks = new ScheduledTasks();;
            try {
                // some code here
            } finally {
                // start annotation
                tasks.reportCurrentTime();
            }
        }
    }

Upvotes: 0

Views: 1808

Answers (2)

GiorgosDev
GiorgosDev

Reputation: 1767

If you are looking for possibility to trigger task scheduling from other Bean then Scheduled annotation is not suitable solution. You can use Task scheduler instead which is used by Spring when it schedules tasks of Scheduled annotation on the background. So the steps would be: 1) Configure task scheduler bean

@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
    ThreadPoolTaskScheduler threadPoolTaskScheduler
      = new ThreadPoolTaskScheduler();
    threadPoolTaskScheduler.setPoolSize(5);
    threadPoolTaskScheduler.setThreadNamePrefix(
      "ThreadPoolTaskScheduler");
    return threadPoolTaskScheduler;
}

2) Inject it in the bean you want to trigger scheduling

@Autowired ThreadPoolTaskScheduler scheduler;

3) Schedule task in the place you want to trigger the scheduling with parameters you want.

taskScheduler.schedule(
new Runnabletask("Specific time, 3 Seconds from now"),
  new Date(System.currentTimeMillis + 3000)
);

Read http://www.baeldung.com/spring-task-scheduler for more details

Upvotes: 0

pvpkiran
pvpkiran

Reputation: 27018

You can enable scheduling even without @SpringBootApplication. Jut use @EnableScheduling on any bean in your project.

@EnableScheduling is not bound to spring boot applications only. It is a an annotation under spring framework(not spring boot jar). So any spring application can direct framework to look for @Scheduled annotation by enabling scheduling with @EnableScheduling.

You can put it on any spring bean. For example

@Configuration
@EnableScheduling
public class AppConfig {

     // various @Bean definitions

}  

or even on the class where you have @Scheduled method

Upvotes: 1

Related Questions