Scheduling Task
Scheduling Task include two steps. The First one is to add @EnableScheduling in the application, the second is the put @Scheduled on the top of the task/method.
Put @EnableScheduling at the Application class
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class); } }
Put @Scheduled(cron = "* * * * * *") on the top of the task/method.
Put @Scheduled(cron = “* * * * * *”) on the top of the task/method. The method must return void. The *s are representing Second, Minute, Hour, Day of Month, Month of Year, Day of Week, similar to cron job in Linux/Unix environment. eg: Run a task every second:
@Scheduled(cron = "*/1 * * * * *") void serviceMethod() { System.out.println("serviceMethod has been run"); }
eg: Run a task every day on 23:59
@Scheduled(cron = "* 59 23 * * *") void serviceMethod() { System.out.println("serviceMethod has been run"); }
There are other scheduled type can be used, such as fixedRate. eg: Execute the annotated method with a fixed period between invocations. Run a task every second.
@Scheduled(fixedRate=1000L) void serviceMethod() { System.out.println("serviceMethod has been run"); }