Java simple timing tasks

@Scheduled

  There are many ways to write timed tasks. I think the easiest way is to use annotations. If your project uses the spring boot framework, you can complete it in three steps:

One, add the @EnableScheduling annotation to the entry class declaration

 

 
  1. /**

  2. * 启动

  3. *

  4. */

  5. @SpringBootApplication

  6. @EnableScheduling

  7. public class Application {

  8. public static void main(String args[]) {

  9. SpringApplication.run(Application.class, args);

  10. }

  11. }

Second, create a class, add @Component annotation

 
  1. @Component

  2. public class Task {

  3.  
  4. }

Three, create method, add @Scheduled annotation

 
  1. @Scheduled(cron = "${task.cron.tradeData}")

  2. public void getTradeData() {

  3.  
  4. }

(Here cron is taken from the configuration file, as follows)

task:
   cron:
     tradeData: 0 1 0 * * ?

It seems simple, but there are many pits hidden, and you fall into it accidentally, such as:

(1) This method cannot have parameters

(2) This method cannot have a return value

(3) This category cannot include other methods with any annotations (Discover New World)

Violation of any one, the timing will not take effect!

Guess you like

Origin blog.csdn.net/qq_39809613/article/details/112566155
Recommended