SpringBoot integrates scheduled tasks

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.

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 @Compomenton 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()));
    }
}

@CompomentUsed to indicate that this is a Spring-managed bean
@Scheduledis an annotation on a method. The method of adding this annotation is a single scheduled task. There are two ways to define:

  1. @Scheduled(fixedRate = 3000)
    Declare the method as a scheduled task via @Scheduled and execute it at a fixed time using the fixedRate attribute

  2. @Scheduled(cron = "0 0/10 * * * ?")
    Use cron expressions to execute at a specified time, here is every 10 minutes;

result

WeChat screenshot_20180413161248.png

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325544857&siteId=291194637