Search code examples
springspring-mvcspring-bootscheduled-tasksscheduling

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


Solution

  • 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.