@EnableScheduling在春天

时间:2016-12-29 09:43:36

标签: spring spring-boot

我是Spring Boot的新手。想在我的Spring Boot应用程序中启用@EnableScheduling和@Scheduled。如下所示,但我如何调用它。

       @EnableScheduling
       public class Application {
           public static void main(String[] args) {
           SpringApplication.run(Application.class, args);
       }

2 个答案:

答案 0 :(得分:0)

我们可以使用Spring @Scheduled注释.Below是要使用的代码 春季启动。

        import org.springframework.boot.SpringApplication;
        import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
        import org.springframework.boot.autoconfigure.SpringBootApplication;
        import org.springframework.boot.builder.SpringApplicationBuilder;
        import org.springframework.boot.context.web.SpringBootServletInitializer;
        import org.springframework.context.annotation.ComponentScan;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.scheduling.annotation.EnableScheduling;


        @SpringBootApplication
        @Configuration
        @ComponentScan
        @EnableAutoConfiguration
        @EnableScheduling
        public class Application extends SpringBootServletInitializer{
           public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
           }

           @Override
           protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
               return application.sources(Application.class);
           }

           private static Class<Application> applicationClass = Application.class;

        }
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;


    @Component
    public class ScheduledTasks {

            @Scheduled(cron = "0 39 00 * * ?")
            public void scheduleFixedDelayTask() {
                System.out.println("Fixed delay task - " + System.currentTimeMillis()/1000);
            }



    }

控制台输出:

修正延迟任务 - 1482952140

答案 1 :(得分:0)

关于您的问题,有一个很好的教程:https://spring.io/guides/gs/scheduling-tasks/

您需要使用@EnableScheduling注释应用程序:

@EnableScheduling
public class SpringGuideApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringGuideApplication.class, args);
    }
}

然后在您的课程中:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class Scheduler {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private static final Logger log = LoggerFactory.getLogger(Scheduler.class);

    @Scheduled(fixedRate = 10000)
    public void reportCurrentTime() {
        log.info("Scheduler: the time is now {}", dateFormat.format(new Date()));
    }
}