天天看点

java定时器(2)--Spring定时器的使用

对于使用Spring框架的project而言,使用Spring框架中集成的SpringTask无非是一个很好选择。下面就是在spring配置文件中添加相应配置,以支持定时任务的注解实现的方法。

(1).在spring-mvc.xml文件中头部声明加入(下面的步骤均是在spring配置文件加入):

<!-- beans里添加:-->  
xmlns:task="http://www.springframework.org/schema/task" 
<!-- xsi:schemaLocation里添加:-->  
http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-3.1.xsd 
           

(2).启用注解驱动的定时任务的方式

<task:annotation-driven scheduler="scheduler"/> 
           

(3).SpringTask默认是单线程执行的,无论有多少方法都要排队执行。 多任务并行执行需要设置’pool-size’参数

<task:scheduler id="scheduler" pool-size="10" />
           

代码实现:

package com.project.controller.task;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component//1
public class testTimeTask {
    @Scheduled(cron = "0 0/2 * * * ?")//2
    public void test1() throws ParseException {
        System.out.println("阻塞线程触发");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date date = sdf.parse("2018-02-26 12-58-00");
        long longDate = date.getTime();
        do{
        }while(longDate-System.currentTimeMillis()>0);
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void test2() {
        Date dt = new Date();  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");  
        System.out.println("TEST2定时执行 :"+sdf.format(dt));
    }
    @Scheduled(cron = "0 0/1 * * * ?")
    public void test3() {
        Date dt = new Date();  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");  
        System.out.println("TEST3定时执行 :"+sdf.format(dt));
    }
}
           

注解1去掉的话那么这个就是一个普通的类,注解2去掉的话那么这个类就是普通的方法。

一些表达式:

工具:在线生产表达式,超实用。http://cron.qqe2.com/