spring 定时器配置

来源:互联网 发布:axure 8.0 mac 破解版 编辑:程序博客网 时间:2024/05/22 07:03

 

  1.  命名空间

    首先添加命名空间  在配置文件中applicationContext.xml



    xmlns:task="http://www.springframework.org/schema/task"   http://www.springframework.org/schema/task      http://www.springframework.org/schema/task/spring-task-3.1.xsd   



  2.   task任务扫描注解
    <task:annotation-driven/>   
  3. <context:component-scan base-package="com.test"/> 

     

    扫描位置 <context:component-scan base-package="com.core" />

     
  4. 写自己的定时方法
    <pre name="code" class="plain">@Service("taskService")public class TaskServiceImpl implements TaskService{@Scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次public void myTest() { System.out.println("------"+System.currentTimeMillis());}}
    <pre name="code" class="plain">public interface TaskService {public void myTest() ;}


    注意:定时器方法是不能有参数和返回值的Assert.isTrue(void.class.equals(method.getReturnType()),"Onlyvoid-returning methods may be annotated with @Scheduled.");Assert.isTrue(method.getParameterTypes().length == 0,"Only no-arg methods may be annotated with @Scheduled.");这是时间的设置规则 
    org.springframework.scheduling.quartz.CronTriggerBean允许你更精确地控制任务的运行时间,只需要设置其cronExpression属性。 
    一个cronExpression表达式有至少6个(也可能是7个)由空格分隔的时间元素。从左至右,这些元素的定义如下: 
    1.秒(0–59) 2.分钟(0–59) 3.小时(0–23) 
    4.月份中的日期(1–31) 5.月份(1–12或JAN–DEC) 
    6.星期中的日期(1–7或SUN–SAT) 7.年份(1970–2099) 0 0 10,14,16 * * ? 
    每天上午10点,下午2点和下午4点 
    0 0,15,30,45 * 1-10 * ? 
    每月前10天每隔15分钟 
    30 0 0 1 1 ? 2012 
    在2012年1月1日午夜过30秒时 
    0 0 8-5 ? * MON-FRI 
    每个工作日的工作时间 各个时间可用值如下:  
    秒0-59 , - * / 分0-59 , - * / 小时0-23 , - * / 
    日1-31 , - * ? / L W C 月1-12 or JAN-DEC , - * / 
    周几1-7 or SUN-SAT , - * ? / L C # 年(可选字段) empty, 1970-2099 , - * / 


0 0
原创粉丝点击