Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式。
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
<task:annotation-driven />
<context:component-scan base-package="com._21cn.flowgate.*" />
@Component
public class MyTask {
@Scheduled(cron = "0/3 * * * * ?")
public void myjob() {
System. out.println( "task execing ...");
}
<bean id ="taskTest" class= "com._21cn.flowgate.self.web.TaskJob" ></bean > <task:scheduled-tasks > <!--这里表示的是每隔5/10秒执行一次 --> <task:scheduled ref ="taskTest" method="show" cron= "*/5 * * * * ?" /> <task:scheduled ref ="taskTest" method="print" cron= "*/10 * * * * ?"/> </task:scheduled-tasks >
public class TaskJob {
void show(){
System. out.println( "5s 执行一次。。。。" );
}
void print(){
System. out.println( "10s 执行一次。。。。" );
}
}
【注意】
测试有两种方式
1、启动已经配置好的sping项目
2、
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestMain { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); } }
这种方式,我一直提示类找不到。
可以使用以下方式解决:
1.加上classpath:前缀 ApplicationContext ctx=new FileSystemXmlApplicationContext("classpath:applicationContext.xml"; 2.加上file:把路径写全 ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext ctx=new ClassPathXmlApplicationContext("file:F:/workspace/SpringExercis/src/applicationContext.xml"); 如果仅仅是测试,最简单的方法还是把xml放在src下方便
【附】
CRON表达式 含义 "0 0 12 * * ?" 每天中午十二点触发 "0 15 10 ? * *" 每天早上10:15触发 "0 15 10 * * ?" 每天早上10:15触发 "0 15 10 * * ? *" 每天早上10:15触发 "0 15 10 * * ? 2005" 2005年的每天早上10:15触发 "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发 "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发 "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发 "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发 "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发 "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
【参考】
http://my.oschina.net/u/559635/blog/389558
原文:http://www.cnblogs.com/Hughzm/p/5197762.html