SpringBoot开发详解(十二) -- SpringBoot中执行定时任务

来源:互联网 发布:微商做图软件有哪些 编辑:程序博客网 时间:2024/06/05 11:19

最近在项目中一直使用定时任务完成一些业务逻辑,比如天气接口的数据获取,定时发送短信,邮件。以及商城中每天用户的限额,定时自动收货等等。定时器在项目中是我们常常会使用到的一个手段,今天我们就来看下在SpringBoot中如何集成定时任务。

定时任务在Spring Boot中的集成

在启动类中加入开启定时任务的注解:

在SpringBoot中使用定时任务相当的简单。首先,我们在启动类中加入@EnableScheduling来开启定时任务。

/** * 启动类 */@RequestMapping(value = "/")@RestController@SpringBootApplication@MapperScan(basePackages = "com.zzp.dao")@Configuration@EnableSwagger2@EnableSchedulingpublic class Round1Application {    @RequestMapping(value = "/",method = RequestMethod.GET)    public String helloWorld(){        return "Hello World";    }    public static void main(String[] args) {        SpringApplication.run(Round1Application.class, args);    }    @Bean    public Docket createApi(){        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()                .apis(RequestHandlerSelectors.basePackage("com.zzp.controller"))                .paths(PathSelectors.any())                .build();    }    private ApiInfo apiInfo(){        return new ApiInfoBuilder()                .title("API文档")                .description("API使用即参数定义")                .termsOfServiceUrl("http://blog.csdn.net/qq_31001665")                .contact("ZZP")                .version("0.1")                .build();    }}

之后我们直接创建实现定时任务的Service即可

@Componentpublic class QuartzService {//    每分钟启动    @Scheduled(cron = "0 0/1 * * * ?")    public void timerToNow(){        System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));    }}

我们已经完成定时任务的所有编写,是不是很简单呢,我们来启动项目看下:

这里写图片描述
OK,没有问题,我们已经可以看到控制台打印出了我们需要的信息。

作为定时器,最重要的一点就是何时运行这段代码,那在SpringBoot也提供了多种实现,以下我们来看一下如何配置定时器的启动时间。

@Scheduled

我们之前是使用cron表达式来制定每分钟启动一次定时器,相信做过SpringMVC的同学应该对cron表达式相当熟悉了,除了该表达式外,我们还可以使用fixedRate,fixedDelay等来作为时间配置。我们先来看一段代码:

    @Scheduled(fixedRate = 5000)    public void timerToZZP(){        System.out.println("ZZP:" + new Random().nextLong() + new SimpleDateFormat("HH:mm:ss").format(new Date()));    }    @Scheduled(fixedDelay = 50000)    public void timerToReportCount(){        for (int i = 0; i < 10; i++){            System.out.println("<================its" + i + "count===============>" + new SimpleDateFormat("HH:mm:ss").format(new Date()));        }    }    @Scheduled(initialDelay = 50000,fixedRate = 6000)    public void timerToReport(){        for (int i = 0; i < 10; i++){            System.out.println("<================delay :" + i + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "count===============>");        }    }

这段代码中我分别使用了fixedRate,fixedDelay,initialDelay,它们分别代表什么含义呢?不要着急,我们先来看一下效果:

这里写图片描述

这里写图片描述

大家看到第一张图片中输出的ZZP:254779489776178507600:15:14是从00:15:14开始,并且每5秒打印一次,由此可知:
项目启动时间00:15:09(这对理解之后的initialDelay有用)

fixedRate:

上一次 启动时间点之后 X秒执行一次

同时我们可以看到<================delay :000:15:59count===============>和<================its0count===============>00:15:59都是从00:15:59开始的,也就是项目开始后的50秒之后,由此可知:

fixedDelay:

上一次 结束时间点之后 每X秒执行一次

我们通过第二张图可以看到之后的<================delay :000:15:59count===============>是间隔6秒执行的,由此我们可知:

initialDelay:

第一次延迟 X秒执行,之后按照fixedRate的规则每X秒执行

以上就是在SpringBoot中定时器的使用,是不是感觉很简单呢?我们下次再见!

以上所有的代码我已经上传到GitHub

round1-springboot

如果心急的小伙伴也可以去clone我已经完成的项目,这个项目中把一些常用功能都写了,并且都写注释啦!!!也希望大家能帮我点个赞哦~~~

MySpringBoot