使用spring提供的@Scheduled注解创建定时任务

使用方法

操作非常简单,只要按如下几个步骤配置即可

1. 导入jar包或添加依赖,其实定时任务只需要spring-context即可,当然起服务还需要spring-web;

2. 编写定时任务类和方法,在方法上加@Scheduled注解,注意定时方法不能有返回值,如果采用包扫描方式注册bean,还需要在类上加组件注解;

3. 在spring容器中注册定时任务类;

4. 在spring配置文件中开启定时功能。

示例Demo

maven依赖

<dependency>
  <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.6.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.1.6.RELEASE</version>
</dependency>

定时任务类

@Component(value = "scheduleJob")
public class ScheduleJob {

    /**
     * 固定间隔时间执行任务,单位为微秒
     */
    @Scheduled(fixedDelay = 2000)
    public void timeJob() {
        System.out.println("2s过去了......");
    }

    /**
     * 使用cron表达式设置执行时间
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void cronJob() {
        System.out.println("cron表达式设置执行时间");
    }
}

spring配置文件——注册定时任务类,或将定时任务类所在的包扫描进去

<?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"
       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">

    <!--扫描指定包下加了组件注解的bean-->
    <context:component-scan base-package="cn.monolog.diana.schedule" />

</beans>

spring配置文件——开启定时功能

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">

    <!--开启定时功能-->
    <task:executor id="executor" pool-size="10" queue-capacity="128" />
    <task:scheduler id="scheduler" pool-size="10" />
    <task:annotation-driven executor="executor" scheduler="scheduler" />

</beans>

启动服务后,控制台会输出如下语句

2s过去了......
2s过去了......
cron表达式设置执行时间
2s过去了......
2s过去了......
2s过去了......
cron表达式设置执行时间
2s过去了......
2s过去了......

指定定时任务执行时间的方式

从上面的demo可以看出,定时任务的执行时间主要有两种设置方式:

1. 使用@Scheduled注解的fixedDelay属性,只能指定固定间隔时长;

2. 使用@Scheduled注解的cron属性,可以指定更丰富的定时方式。

那么问题来了,这个cron表达式该怎么写?

猜你喜欢

转载自www.cnblogs.com/dubhlinn/p/10739851.html