java-并发-定时任务ScheduleExecutorService和spring用法

一. ScheduleExecutorService配置

说明
注意问题:

  • 我们需要捕获最上层的异常,防止出现异常中止执行,导致周期性的任务不再执行。
  • 如果执行的任务大于我们指定的执行间隔,比如scheduleAtFixedRate方法;当执行任务的时间大于我们指定的间隔时间时,等待任务执行完毕,再开启新的线程;

方法区别

  • scheduleAtFixedRate从上一个任务开始计算,频率固定;
  • scheduleWithFixedDealy从上一个任务结束时开始计算,频率不固定;

scheduleAtFixedRate

    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,		//执行线程
                                                  long initialDelay,	//初始化延迟
                                                  long period,			//两次执行最小间隔
                                                  TimeUnit unit);		//计时单位

scheduleWithFixedDelay

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,  	//执行线程
                long initialDelay,  			//初始化延时
                long delay,  					//前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
                TimeUnit unit);  				//

使用例子
例子1:以固定周期频率执行任务

public static void executeFixedRate() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    executor.scheduleAtFixedRate(  
            new EchoServer(),  
            0,  
            100,  
            TimeUnit.MILLISECONDS);  
}  

例子2:以固定延迟时间进行执行

public static void executeFixedDelay() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    executor.scheduleWithFixedDelay(  
            new EchoServer(),  
            0,  
            100,  
            TimeUnit.MILLISECONDS);  
}  

例子3:每天晚上8点执行一次,每天定时安排任务进行执行

public static void executeEightAtNightPerDay() {  
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
    long oneDay = 24 * 60 * 60 * 1000;  
    long initDelay  = getTimeMillis("20:00:00") - System.currentTimeMillis();  
    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;  
  
    executor.scheduleAtFixedRate(  
            new EchoServer(),  
            initDelay,  
            oneDay,  
            TimeUnit.MILLISECONDS);  
} 

//获取指定时间对应的毫秒数
private static long getTimeMillis(String time) {  
    try {  
        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
        return curDate.getTime();  
    } catch (ParseException e) {  
        e.printStackTrace();  
    }  
    return 0;  
} 

任务代码如下

class EchoServer implements Runnable {  
    @Override  
    public void run() {  
        try {  
            Thread.sleep(50);  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        System.out.println("This is a echo server. The current time is " +  
                System.currentTimeMillis() + ".");  
    }  
} 

二. Spring配置

除了我们自己实现定时任务之外,我们可以使用Spring帮我们完成这样的事情。

<bean id="myTimedTask" class="com.study.MyTimedTask"/> 
<bean id="doMyTimedTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">  
    <property name="targetObject" ref="myTimedTask"/>  
    <property name="targetMethod" value="execute"/>  
    <property name="concurrent" value="false"/>  
</bean>  
<bean id="myTimedTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
    <property name="jobDetail" ref="doMyTimedTask"/>  
    <property name="cronExpression" value="0 0 2 * ?"/>  
</bean>  
<bean id="doScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
    <property name="triggers">  
        <list>  
            <ref local="myTimedTaskTrigger"/>  
        </list>  
    </property>  
</bean> 
posted @ 2016-09-19 14:48  zhangshihai1232  阅读(1777)  评论(0编辑  收藏  举报