09.07 Spring Scheduled

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、写一个简单例子:

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");
@Scheduled(cron = "0/5 * * * * ?")
public void exejob() {
System.out.println(sdf_yyyyMMddHHmmss.format(new Date()) + " :执行中。。。");
}
}

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

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

还可以在一个类上写多个任务:

@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 执行中。。。");
}
}
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 执行中。。。


分享到:


相關文章: