在Spring项目中使用@Scheduled注解定义简单定时任务

如题所示,有时候我们需要在Web项目中配置简单的定时任务,而且因为任务并不复杂不想使用定时调度框架(PS:Quartz、ActiveMQ 、Kafka等),这时就可以考虑使用@Scheduled注解来定义简单的定时任务。其全部配置如下:

(1)在Spring的配置文件中添加定时任务相关配置:

xml配置的头文件中添加:

1
xmlns:task="http://www.springframework.org/schema/task"

以及在xsi:schemaLocation中添加:

1
2
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd

最后添加:

1
2
3
4
<context:component-scan base-package="cn.zifangsky.task" />
<task:executor id="executor" pool-size="5"/>
<task:scheduler id="scheduler" pool-size="10"/>
<task:annotation-driven executor="executor" scheduler="scheduler"/>

其中,这里首先定义了Spring自动扫描定时任务所在的package,也就是“cn.zifangsky.task”。接着定义了两个线程池以及启用定时任务的扫描机制

(2)添加测试任务:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package cn.zifangsky.task;
 
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class SimpleSpringTask {
     
    /**
     * 每次任务执行完之后的2s后继续执行
     */
    @Scheduled(fixedDelay=2000)
    public void say(){
        Date current = new Date();
        Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         
        System.out.println("--------" + format.format(current) + "---------");
    }
     
    /**
     * 0秒的时候打印
     */
    @Scheduled(cron="0 * * * * ?")
    public void print(){
         
        System.out.println("当前是整分!!!");
    }
     
}

上面第一个任务定义了每个任务执行完之后的2s之后再次执行,如果需要强制指定每隔多少时间执行一次任务,可以将上面的fixedDelay改成fixedRate,如:

1
2
3
4
5
6
7
8
9
10
/**
 * 每隔两秒执行一次本方法
 */
@Scheduled(fixedRate=2000)
public void say(){
    Date current = new Date();
    Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     
    System.out.println("--------" + format.format(current) + "---------");
}

当然,上面的第二种任务形式类似于Linux下的crontab定时任务,几个参数位分别表示:秒、分钟、小时、天(每月中的天)、月份以及星期

注:如果想要了解更多的关于Linux中使用crontab命令的用法可以参考我的这篇文章:https://www.zifangsky.cn/591.html

(3)测试:

运行这个项目后,最后控制台中的输出如下:

在Spring项目中使用@Scheduled注解定义简单定时任务



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1877598,如需转载请自行联系原作者