Spring @Scheduled任务调度器

本文介绍Spring框架中@Scheduled注解的使用方法,演示如何配置并实现每5秒执行一次的任务,同时展示如何在同一类中定义多个定时任务并行执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring @Scheduled是Spring计划任务的一种很简洁的实现。用来替代Quartz的方案。

要使用此特性,需要Spring3.2以上版本。用法:

1、在xml的配置中,需要加入:

            http://www.springframework.org/schema/task

            http://www.springframework.org/schema/task/spring-task-3.2.xsd"

2、写一个简单例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * Created by leizhimin on 2014/8/16.
 *
 * @author leizhimin 2014/8/16 17:46
 */
@Component
@Lazy(false)
public class TestJob {
    public static SimpleDateFormat sdf_yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
 
    //表示没5秒钟调用输出一次
    @Scheduled(cron = "0/5 * * * * ?")
    public void exejob() {
        System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :执行中。。。");
    }
}


每隔5秒中就会输出一条信息。


------------------------------------

还可以在一个类上写多个任务同时触发执行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Component
@Lazy(false)
public class TestJob {
    public static SimpleDateFormat sdf_yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss");
 
 
    @Scheduled(cron = "0/5 * * * * ?")
    public void exejob1() {
        System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :AAAA 执行中。。。");
    }
 
    @Scheduled(cron = "0/5 * * * * ?")
    public void exejob2() {
        System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :BBBB 执行中。。。");
    }
    @Scheduled(cron = "0/5 * * * * ?")
    public void exejob3() {
        System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :CCCC 执行中。。。");
    }
}
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
20141010225850 :AAAA 执行中。。。
20141010225850 :BBBB 执行中。。。
20141010225850 :CCCC 执行中。。。
20141010225855 :AAAA 执行中。。。
20141010225855 :BBBB 执行中。。。
20141010225855 :CCCC 执行中。。。
20141010225900 :AAAA 执行中。。。
20141010225900 :BBBB 执行中。。。
20141010225900 :CCCC 执行中。。。
20141010225905 :AAAA 执行中。。。
20141010225905 :BBBB 执行中。。。
20141010225905 :CCCC 执行中。。。
20141010225910 :AAAA 执行中。。。
20141010225910 :BBBB 执行中。。。
20141010225910 :CCCC 执行中。。。
20141010225915 :AAAA 执行中。。。
20141010225915 :BBBB 执行中。。。
20141010225915 :CCCC 执行中。。。
20141010225920 :AAAA 执行中。。。
20141010225920 :BBBB 执行中。。。
20141010225920 :CCCC 执行中。。。
20141010225925 :AAAA 执行中。。。
20141010225925 :BBBB 执行中。。。
20141010225925 :CCCC 执行中。。。
20141010225930 :AAAA 执行中。。。
20141010225930 :BBBB 执行中。。。
20141010225930 :CCCC 执行中。。。
20141010225935 :AAAA 执行中。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值