Spring 在 Spring Boot 2.0.0.M6 中调度
Spring Scheduling in Spring Boot 2.0.0.M6
我使用 Spring 初始化程序生成了一个 Spring 启动 Web 应用程序,嵌入 Tomcat,Thymeleaf 模板引擎,并打包为可执行 JAR 文件。
使用的技术:
Spring 开机 2.0.0.M6 , Java 8, maven.
我创建了这个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()));
}
}
期待每分钟都能看到消息
和我的主要 class
@SpringBootApplication
@EnableScheduling
@Import({SecurityConfig.class})
public class IberiaWebUtilsApplication {
public static void main(String[] args) {
SpringApplication.run(IberiaWebUtilsApplication.class, args);
}
}
但我在控制台中没有看到任何消息
您应该使用 Logger 更改 System.out.println(...)
以便查看消息并将 class 声明为 Spring 托管 bean,如 g00glen00b 在他的回答中所述。
private static final Logger log = Logger.getLogger(IberiaAssetHandlerJob.class);
log.info("The time is now {}" + dateFormat.format(new Date()));
@Scheduled
注释仅适用于 Spring 托管 bean。您没有在 IberiaAssetHandlerJob
上放置 @Component
注释,也没有手动创建 bean(使用 @Bean
注释)。
此外,请注意 PrintStream
(System.out
使用的基础 class)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 在他的回答中提到)。这也允许您使用 {}
等占位符,例如:
logger.info("The time is now {}", dateFormat.format(new Date()));
在这种情况下,请确保使用多个参数,而不是将所有内容连接到一个字符串。
我使用 Spring 初始化程序生成了一个 Spring 启动 Web 应用程序,嵌入 Tomcat,Thymeleaf 模板引擎,并打包为可执行 JAR 文件。
使用的技术:
Spring 开机 2.0.0.M6 , Java 8, maven.
我创建了这个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()));
}
}
期待每分钟都能看到消息
和我的主要 class
@SpringBootApplication
@EnableScheduling
@Import({SecurityConfig.class})
public class IberiaWebUtilsApplication {
public static void main(String[] args) {
SpringApplication.run(IberiaWebUtilsApplication.class, args);
}
}
但我在控制台中没有看到任何消息
您应该使用 Logger 更改 System.out.println(...)
以便查看消息并将 class 声明为 Spring 托管 bean,如 g00glen00b 在他的回答中所述。
private static final Logger log = Logger.getLogger(IberiaAssetHandlerJob.class);
log.info("The time is now {}" + dateFormat.format(new Date()));
@Scheduled
注释仅适用于 Spring 托管 bean。您没有在 IberiaAssetHandlerJob
上放置 @Component
注释,也没有手动创建 bean(使用 @Bean
注释)。
此外,请注意 PrintStream
(System.out
使用的基础 class)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 在他的回答中提到)。这也允许您使用 {}
等占位符,例如:
logger.info("The time is now {}", dateFormat.format(new Date()));
在这种情况下,请确保使用多个参数,而不是将所有内容连接到一个字符串。