前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(10)SpringBoot创建定时任务

(10)SpringBoot创建定时任务

作者头像
IT云清
发布2022-05-07 16:22:06
2660
发布2022-05-07 16:22:06
举报
文章被收录于专栏:IT云清IT云清

   摘要:本文主要讲解使用SpringBoot创建定时任务。

项目中经常会需要做一些定时处理的任务,比如每间隔多久做个统计,发个邮件,清理个数据。这时候就要用到定时任务,SpringBoot中,创建定时任务非常简单,具体步骤如下:

1.注解开启定时任务

在程序的启动类上加上@EnableScheduling注解,就会自动启用定时任务。

代码语言:javascript
复制
package com.java4all;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@SpringBootApplication
@EnableAutoConfiguration
@RestController
@EnableScheduling
@MapperScan("com.java4all.dao")
public class TmallApplication {
    public static void main(String[] args) {
        SpringApplication.run(TmallApplication.class, args);
    }
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "欢迎登陆:"+ LocalDateTime.now();
    }
}
2.创建定时任务

单独创建一个类,用来存放定时任务,然后在每个定时任务方法上,用注解标明定时任务的执行周期。我这里以每间隔10秒打印一下当前系统时间为例,注意@Component注解。

代码语言:javascript
复制
package com.java4all.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
 * Author: momo
 * Date: 2018/4/9
 * Description:定时任务类
 */
@Component
public class ScheduledTask {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Scheduled(fixedRate = 10000)
    public void printTime(){
        logger.info("定时任务,现在时间:"+System.currentTimeMillis());
    }
}
3.@Scheduled的几种用法
  • @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
  • @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
  • @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
  • @Scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则

注意,这里的时间,单位是毫秒,1秒=1000毫秒

4.运行项目

项目启动后,我们就会在控制台看到每隔10秒会打印当前时间。

640?wx_fmt=png
640?wx_fmt=png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.注解开启定时任务
  • 2.创建定时任务
  • 3.@Scheduled的几种用法
  • 4.运行项目
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档