竹笋

注册

 

发新话题 回复该主题

SpringBoot2x教程使用Sch [复制链接]

1#

我们在编写SpringBoot应用中经常会遇到这样的场景,比如:我需要定时地发送一些短信、邮件之类的操作,也可能会定时地检查和监控一些标志、参数等。

创建定时任务

在SpringBoot中编写定时任务是非常简单的事,下面通过实例介绍如何在SpringBoot中创建定时任务,实现每过5秒输出一下当前时间。

在SpringBoot的主类中加入

EnableScheduling注解,启用定时任务的配置

SpringBootApplication

EnableSchedulingpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}

创建定时任务实现类

ComponentpublicclassScheduledTasks{privatestaticfinalSimpleDateFormatdateFormat=newSimpleDateFormat("HHss");

Scheduled(fixedRate=)publicvoidreportCurrentTime(){log.info("现在时间:"+dateFormat.format(newDate()));}}

运行程序,控制台中可以看到类似如下输出,定时任务开始正常运作了。

-07-:56:56.INFO---[main]c.d.chapter71.Chapter71Application:StartedChapter71Applicationin1.seconds(JVMrunningfor1.)-07-:57:01.INFO---[scheduling-1]
分享 转发
TOP
发新话题 回复该主题