简体   繁体   中英

Spring Scheduling in Spring Boot 2.0.0.M6

I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

Technologies used:

Spring Boot 2.0.0.M6 , Java 8, maven.

I've created this class

com.iberia.task.scheduled

    public class IberiaAssetHandlerJob {


        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

        @Scheduled(cron = "0 * * * * ?")
        public void reportCurrentTime() {

            System.out.println("The time is now {}" + dateFormat.format(new Date()));

        }
    }

expecting to see the message every minute

and my main class

@SpringBootApplication
@EnableScheduling
@Import({SecurityConfig.class})
public class IberiaWebUtilsApplication {

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

but I don't see any message in the console

You should change System.out.println(...) with a Logger in order to see the message and declare class as Spring managed bean as g00glen00b states in his answer.

private static final Logger log = Logger.getLogger(IberiaAssetHandlerJob.class);

log.info("The time is now {}" + dateFormat.format(new Date()));

The @Scheduled annotation only works for Spring managed beans. You didn't put a @Component annotation on top of IberiaAssetHandlerJob , nor did you manually create a bean (using the @Bean annotation).


Also, be aware that PrintStream (the underlying class used by System.out ) isn't necessarily thread-safe , so if you have other threads writing to System.out as well, then you may get strange results, that's why it's recommended to use a logging framework (like lzagkaretos mentioned in his answer). This also allows you to use placeholders like {} as well, for example:

logger.info("The time is now {}", dateFormat.format(new Date()));

Make sure to use multiple arguments rather than concatenating everything to a single string in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM