使用@Scheduled实现定时任务

1.maven 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lxy</groupId>
  <artifactId>schedule_demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.2.6.RELEASE</version>
    </dependency>
  </dependencies>
</project>

2.使用springboot,RootApplication位于根目录下

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class RootApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(RootApplication .class, args);
    }
}

 3.设置时间

 3.1 创建一个Java类(MyTimerManager),添加一个无参无返回值的方法,在方法上使用@Scheduled注解修饰;

 3.2 创建的Java类要成为Spring可管理的Bean,可以直接写在XML里,也可以使用@Component组件

          可以通过注解@Scheduled 可以作为一个触发源添加到一个方法中,例如,@Scheduled(fixedDelay=3000)将以一个固定延迟时间3秒钟调用一次执行,这个周期是以上一个调用任务的完成时间为基准,在上一个任务完成之后,3s后再次执行;

    如果需要以固定速率执行,只要将注解中指定的属性名称改成fixedRate即可,@Scheduled(fixedRate=3000)将以一个固定速率3s来调用一次执行,这个周期是以上一个任务开始时间为基准,从上一任务开始执行后3s再次调用:

        如果需要以固定延迟和固定速率的任务,可以指定一个初始延迟表示该方法在第一被调用执行之前等待的毫秒数: @Scheduled(initialDelay=1000, fixedRate=5000)

          如果简单的定期调度不能满足,则可以使用cron表达式。例如,下面的方法将只会在工作日执行:@Scheduled(cron = "50 40 21 * * ?"),   还可以通过使用zone属性来指定cron表达式被调用的时区。

@Component
public class MyTimerManager {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    //每3秒执行一次
    @Scheduled(fixedRate = 3000)
    public void timerRate() {
        System.out.println("每3秒执行一次:"+sdf.format(new Date()));
    }

    //第一次延迟1秒执行,当执行完后3秒再执行
    @Scheduled(initialDelay = 1000, fixedDelay = 3000)
    public void timerInit() {
        System.out.println("init : "+sdf.format(new Date()));
    }

    //每天21点40分50秒时执行
    @Scheduled(cron = "50 40 21 * * ?")
    public void timerCron() {
        System.out.println("current time : "+ sdf.format(new Date()));
    }
}

4.结果展示,改过后的时间 

init : 21:50:42
每3秒执行一次:21:50:44
init : 21:50:45
每3秒执行一次:21:50:47
init : 21:50:48
current time : 21:50:50
每3秒执行一次:21:50:50
init : 21:50:51

5.另外不使用springboot,请参考下面这种方式:

<?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:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
                            http://www.springframework.org/schema/task 
                            http://www.springframework.org/schema/task/spring-task-3.0.xsd 
                            http://www.springframework.org/schema/context 
                            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
         <!--需要扫描的包-->
	<context:component-scan base-package="com.lxy.*"/>
	<!-- 这句是重点 定时器开关-->
    <task:executor id="executor" pool-size="5" />
    <task:scheduler id="scheduler" pool-size="10" />
    <task:annotation-driven executor="executor" scheduler="scheduler" />
</beans>

添加task定时任务的xml文件,配置在spring文件中

@Scheduled注解可以控制方法定时执行,其中有三个参数可选择:

1、fixedDelay控制方法执行的间隔时间,是以上一次方法执行完开始算起,如上一次方法执行阻塞住了,那么直到上一次执行完,并间隔给定的时间后,执行下一次。

2、fixedRate是按照一定的速率执行,是从上一次方法执行开始的时间算起,如果上一次方法阻塞住了,下一次也是不会执行,但是在阻塞这段时间内累计应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。

3、cron表达式可以定制化执行任务,但是执行的方式是与fixedDelay相近的,也是会按照上一次方法结束时间开始算起。

注意:

  1、spring的注解@Scheduled  需要写在实现方法上;

  2、定时器的任务方法不能有返回值(如果有返回值,spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true),不能指向任何的参数;

  3、如果该方法需要与应用程序上下文的其他对象进行交互,通常是通过依赖注入来实现;

  4、实现类上要有组件的注解@Component, 在Spring配置文件中添加三个<task:**** />节点;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值