@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
-
/**
-
* 启动
-
*
-
*/
-
@SpringBootApplication
-
@EnableScheduling
-
public class Application {
-
public static void main(String args[]) {
-
SpringApplication.run(Application.class, args);
-
}
-
}
Second, create a class, add @Component annotation
-
@Component
-
public class Task {
-
}
Three, create method, add @Scheduled annotation
-
@Scheduled(cron = "${task.cron.tradeData}")
-
public void getTradeData() {
-
}
(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!