How to Schedule Tasks in Spring ?


 

Contents

  1. How to schedule a task

  2. What to execute

  3. How to enable scheduling

 

How to schedule a task?

The myScheduledTasks class is scheduled to run periodically or in a certain interval. It is a plain spring component. The @Scheduled annotation can be used on a method to define when it runs. In this case we want that the method is executed after a certain time interval. We call it a task. We also can configure the task to run after a certain delay once the task is executed or we can use a cron format. In this example the task will execute once in 86400000 millisecond or one day.

import org.springframework.schedulling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.inject.Inject;

@Component
public class myScheduledTasks {
   @Inject
   private AppInfo appinfo;

   @Scheduled(fixedrate = 86400000)
   public void print() {
      appinfo.print();
   }
}


What to execute?

Now we have learned how we can schedule a task but what will be executed when the task is started? For that reason I have injected the AppInfo class. Please read my another blog post to understand What the AppInfo class contains. The scheduled task that executes the print() method calls a print() method on the AppInfo object.


How to enable scheduling ?

In the spring boot applications file that contains the main method we annotate the class with @SpringBootApplication that makes the application a spring boot application. We need to annotate the same class to enable scheduling.


A comprehensive example on the same topic can be found on the spring.io guide.



10 views0 comments

Recent Posts

See All