轻量级Spring定时任务(Spring-task)

Spring3.0以后自主开发的定时任务工具,spring-task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式。

第一种:基于注解
1、spring.xml中对应位置加入
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.*" />
2、任意一个测试类
@Component
public class MyTask {
 
     @Scheduled(cron = "0/3 * * * * ?")
     public void myjob() {
           System. out.println( "task execing ...");
     }


第二种:基于xml配置
 
1、在上面基于注解的配置基础上加上
(bean路径指向定时任务执行类)
 <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 >  
2、任意测试类
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表达式,如果不去理解?很容易被用错

1) 每一位表示的是 [ 秒 分 时 日 月 周 年]

2) The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fields, but not the other.

注意着两个概念 day-of-month /day-of-week

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

原文地址:https://www.cnblogs.com/Hughzm/p/5197762.html