加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring Boot配置定时任务

发布时间:2020-12-15 01:53:05 所属栏目:大数据 来源:网络整理
导读:在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计(阅读量统计),数据更新(生成每天的歌单推荐)等。 Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务的配置。下面分两步来配置一个定时任务: 创建定时任务

在项目开发过程中,经常需要定时任务来做一些内容,比如定时进行数据统计(阅读量统计),数据更新(生成每天的歌单推荐)等。

Spring Boot默认已经实现了,我们只需要添加相应的注解就可以完成定时任务的配置。下面分两步来配置一个定时任务:

  1. 创建定时任务
  2. 启动类添加注解

创建定时任务

这里需要用到Cron表达式,如果对Cron表达式不是很熟悉,可以查看。

这是我自定义的一个定时任务:每10s中执行一次打印任务。

</span><span style="color: #0000ff;"&gt;private</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;final</span> SimpleDateFormat simpleDateFormat = <span style="color: #0000ff;"&gt;new</span> SimpleDateFormat("yyyy-MM-dd HH:mm:ss"<span style="color: #000000;"&gt;); @Scheduled(cron </span>= "*/10 * * * * ?"<span style="color: #000000;"&gt;) </span><span style="color: #008000;"&gt;//</span><span style="color: #008000;"&gt; 每10s执行一次,秒-分-时-天-月-周-年</span> <span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;void</span> test() <span style="color: #0000ff;"&gt;throws</span><span style="color: #000000;"&gt; Exception { System.out.println(simpleDateFormat.format(</span><span style="color: #0000ff;"&gt;new</span> Date()) + "定时任务执行咯"<span style="color: #000000;"&gt;); }

}

启动类添加注解

在启动类上面添加@EnableScheduling注解,开启Spring Boot对定时任务的支持。

</span><span style="color: #0000ff;"&gt;public</span> <span style="color: #0000ff;"&gt;static</span> <span style="color: #0000ff;"&gt;void</span><span style="color: #000000;"&gt; main(String[] args) { SpringApplication.run(DemoApplication.</span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt;,args); }

}

执行效果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读