Spring Boot : 定时任务(十)

来源:互联网 发布:淘宝商城女装夏装 编辑:程序博客网 时间:2024/06/04 19:48

目录

  • 目录
  • 单线程定时任务
  • 多线程定时任务

单线程定时任务

SpringBoot提供的定时任务是单线程的。代码很简单。

package cn.milo.controllor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Configuration@EnableScheduling//@Componentpublic class Scheduling {    private final Logger logger = LoggerFactory.getLogger(getClass());    @Scheduled(cron = "0/5 * * * * ?") // 每20秒执行一次    public void scheduler() {        logger.info("定时任务 1");    }}    @Scheduled(cron = "0/5 * * * * ?") // 每20秒执行一次    public void scheduler2() {        logger.info("定时任务 2");    }}

大家可以打印一下线程号,会发现所有定时任务都是串行完成的。但很多时候我们需要好多个定时任务一起进行,且互不干扰。下边介绍并行定时任务。

多线程定时任务

Scheduling.java

package cn.milo.controllor;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;//@Configuration //这里就不用springboot了//@EnableScheduling //这里就不用springboot了@Component //spring直接加载这个类public class Scheduling {    private final Logger logger = LoggerFactory.getLogger(getClass());    @Scheduled(cron = "0/5 * * * * ?") // 每20秒执行一次    public void scheduler() {        logger.info("定时任务 1");    }    @Scheduled(cron = "0/5 * * * * ?") // 每20秒执行一次    public void scheduler2() {        logger.info("定时任务 2");    }}

通过SpringBoot配置Spring方式来指定Spring配置文件
SpringConfig.java

package cn.milo.controllor;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.ImportResource;/** * Created by mac on 2017/8/28. */@Configuration@ImportResource("/spring/applicationContext.xml")public class SpringConfig {}

在src/main/resources/spring下简历spring配置文件
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:task="http://www.springframework.org/schema/task"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">    <!-- Enables the Spring Task @Scheduled programming model -->    <task:executor id="executor" pool-size="5" />    <task:scheduler id="scheduler" pool-size="10" />    <task:annotation-driven executor="executor" scheduler="scheduler" /></beans>
原创粉丝点击