Scheduled tasks are generally used in projects and can be used to process some special tasks regularly. Using timed tasks in SpirngBoot is very simple. You don't need to write a lot of configuration like SpringMVC. You only need to add an @EnableScheduling annotation to the startup class.
Use annotations on classes that use timed tasks and annotations
result
Start the class to start the scheduled task
//开启定时任务
@EnableScheduling
@RestController
@SpringBootApplication
//设置扫描的包名
@ComponentScan(basePackages = {"com.preach.controller"})
public class InchlifcApplication {
public static void main(String[] args) {
SpringApplication.run(InchlifcApplication.class, args);
}
}
Use annotations on classes that use timed tasks and annotations @Compoment
on methods@Scheduled
@Component
public class IndexController {
/**
* 时间间隔,每隔5秒执行一次
*/
@Scheduled(fixedRate = 5000)
public void task() {
System.out.println("现在时间是:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
@Compoment
Used to indicate that this is a Spring-managed bean @Scheduled
is an annotation on a method. The method of adding this annotation is a single scheduled task. There are two ways to define:
@Scheduled(fixedRate = 3000)
Declare the method as a scheduled task via @Scheduled and execute it at a fixed time using the fixedRate attribute@Scheduled(cron = "0 0/10 * * * ?")
Use cron expressions to execute at a specified time, here is every 10 minutes;