基于Spring Boot 实现定时任务

来源:互联网 发布:ccs软件百度云 编辑:程序博客网 时间:2024/05/29 00:34

转自:http://www.tianmaying.com/tutorial/spring-scheduling-task


很多时候,我们有这么一个需求,需要在每天的某个固定时间或者每隔一段时间让应用去执行某一个任务。为了实现这个需求,通常我们会通过多线程来实现这个功能,但是这样我们需要自己做一些比较麻烦的工作。接下来,让我们看看如何使用Spring scheduling task简化定时任务功能的实现。

添加maven依赖

为了方便展示,我们使用Spring Boot来简化我们的Spring配置。因为我们使用的是Spring自带的Scheduling,因此我们只需要引入最进本的spring-boot-starter即可。

<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.2.5.RELEASE</version></parent><properties>    <java.version>1.8</java.version></properties><dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter</artifactId>    </dependency></dependencies>

注意,Spring boot需要JDK8的编译环境。

创建Scheduled Task

让我们创建一个ScheduleTask来实现我们的需求:

@Componentpublic class ScheduledTask {    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    private Integer count0 = 1;    private Integer count1 = 1;    private Integer count2 = 1;    @Scheduled(fixedRate = 5000)    public void reportCurrentTime() throws InterruptedException {        System.out.println(String.format("---第%s次执行,当前时间为:%s", count0++, dateFormat.format(new Date())));    }    @Scheduled(fixedDelay = 5000)    public void reportCurrentTimeAfterSleep() throws InterruptedException {        System.out.println(String.format("===第%s次执行,当前时间为:%s", count1++, dateFormat.format(new Date())));    }    @Scheduled(cron = "*/5 * * * * *")    public void reportCurrentTimeCron() throws InterruptedException {        System.out.println(String.format("+++第%s次执行,当前时间为:%s", count2++, dateFormat.format(new Date())));    }}

可以看到,我们在我们真正需要执行的方法上添加了@Scheduled标注,表示这个方法是需要定时执行的。

@Scheduled标注中,我们使用了三种方式来实现了同一个功能:每隔5秒钟记录一次当前的时间:

  • fixedRate = 5000表示每隔5000ms,Spring scheduling会调用一次该方法,不论该方法的执行时间是多少
  • fixedDelay = 5000表示当方法执行完毕5000ms后,Spring scheduling会再次调用该方法
  • cron = "*/5 * * * * * *"提供了一种通用的定时任务表达式,这里表示每隔5秒执行一次,更加详细的信息可以参考cron表达式。

配置Scheduling

接下来我们通过Spring boot来配置一个最简单的Spring web应用,我们只需要一个带有main方法的类即可:

@SpringBootApplication@EnableSchedulingpublic class App {    public static void main(String[] args) {        SpringApplication.run(App.class, args);    }}

我们先来看看class上的标注:

  • @SpringBootApplication 实际上是了以下三个标注的集合:
    • @Configuration 告诉Spring这是一个配置类,里面的所有标注了@Bean的方法的返回值将被注册为一个Bean
    • @EnableAutoConfiguration 告诉Spring基于class path的设置、其他bean以及其他设置来为应用添加各种Bean
    • @ComponentScan 告诉Spring扫描Class path下所有类来生成相应的Bean
  • @EnableScheduling 告诉Spring创建一个task executor,如果我们没有这个标注,所有@Scheduled标注都不会执行

通过以上标注,我们完成了schedule的基本配置。最后,我们添加main方法来启动一个Spring boot应用即可。

测试

在根目录下执行命令:mvn spring-boot:run,我们可以看到:

alter-text

0 0
原创粉丝点击