定時任務

1、Timer

Timer創建對象時,創建了一個線程來調度任務。

timer.schedule(...) : fixed-delay(注重間隔時間的穩定),若計劃執行時間小於當前時間,則立即執行task,之後按period定時執行task

timer.scheduleAtFixedRate(...) :fixed-rate(注重執行頻率的穩定),若計劃時間小於當前時間,則立即執行一次task,之後根據計劃時間、當前時間和period計算出本該執行的次數,執行計算出的次數,之後再按period定時執行task

<pre code_snippet_id="1664715" snippet_file_name="blog_20160428_1_863739" name="code" class="java">	<span style="font-family: Arial, Helvetica, sans-serif;">private static void useTimer() {</span>
TimerTask timerTask = new TimerTask() {@Overridepublic void run() {System.out.println(Calendar.getInstance().getTime());}};Timer timer = new Timer("testTimer");long delay = 0;long intevalPeriod = 1*1000;// timer.schedule(timerTask, delay);// timer.schedule(timerTask, delay, intevalPeriod);timer.scheduleAtFixedRate(timerTask, delay, intevalPeriod);}

2、ScheduledExecutorService

service.schedule(...) : 只在制定delay時間後執行一次

service.scheduleWithFixedDelay(...) : fixed-delay

service.scheduleAtFixedRate(...) : fixed-rate

<span style="white-space:pre">	</span>private static void useScheduledExecutorService() {
		Runnable task = new Runnable() {
			public void run() {
				System.out.println(Calendar.getInstance().getTime());
//				try {
//					Thread.sleep(2000);
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				}
			}
		};
		ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
//		service.schedule(task, 1000, TimeUnit.MILLISECONDS);
//		service.scheduleWithFixedDelay(task, 0, 1000, TimeUnit.MILLISECONDS);
		service.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS);
	}

3、Spring Quartz

調度工廠 ScheduleFactoryBean

以線程池處理調度任務JobDetail,默認池大小爲10,當調度器中線程都被佔用時,調度任務被阻塞。

配置Triggers

TriggerBean : 需要配置jobDetail、repeatInterval、startDelay

SimpleTriggerBean : 只支持按一定頻率執行任務,如每隔10分鐘

CronTriggerBean : 只支持在指定時間執行任務,如每天12:00

JobDetailBean : 需要配置targetObject、targetMethod、concurrent

MethodInvokingJobDetailFactoryBean :

    <bean id="checkAirAvailAXmlTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"
          lazy-init="false">
        <property name="jobDetail" ref="checkAirAvailAXmlCronMethodInvoke"/>
        <property name="repeatInterval" value="600000"/>
        <property name="startDelay" value="3000"/>
    </bean>
    <bean id="checkAirAvailAXmlCronMethodInvoke" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"
          lazy-init="false">
        <property name="targetObject" ref="checkAirAvailAXmlCron"/>
        <property name="targetMethod" value="exe"/>
        <property name="concurrent" value="false"/>
    </bean>

@Component("checkAirAvailAXmlCron")
public class CheckAirAvailAXmlCron {
    ...
}


4、Spring Task http://gong1208.iteye.com/blog/1773177

配置文件:

1、文件頭配置命名空間

<beans xmlns="http://www.springframework.org/schema/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.0.xsd">
2、配置任務

<task:scheduled-tasks> 
        <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/> 
</task:scheduled-tasks>

<context:component-scan base-package="com.xxx.mytask" />
3、任務

import org.springframework.stereotype.Service;
@Service
public class TaskJob {
    
    public void job1() {
        System.out.println(“任務進行中。。。”);
    }
}


註解:

使用註解@Scheduled

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled {
    public abstract String cron();

    public abstract long fixedDelay();

    public abstract long fixedRate();
}
1、任務
import org.springframework.scheduling.annotation.Scheduled;  
import org.springframework.stereotype.Component;

@Component(“taskJob”)
public class TaskJob {
    @Scheduled(cron = "0 0 3 * * ?")
    public void job1() {
        System.out.println(“任務進行中。。。”);
    }
}
2、配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
	default-lazy-init="false">

	<context:annotation-config />
	<!—spring掃描註解的配置-->
	<context:component-scan base-package="com.xxx.mytask" />
	
        <!—開啓這個配置,spring才能識別@Scheduled註解   -->
        <task:annotation-driven executor="executor" scheduler="scheduler"/>
        <task:scheduler id="scheduler" pool-size="10"/>
        <task:executor id="executor" pool-size="10"/>

如果定時任務很多,可以配置executor線程池,這裏executor的含義和java.util.concurrent.Executor是一樣的,pool-size的大小官方推薦爲5~10。scheduler的pool-size是ScheduledExecutorService線程池,默認爲1。


        <task:scheduled-tasks scheduler="scheduler">
            <task:scheduled ref="reminderProcessor" method="process" cron="0 0 12 * * ?" />
        </task:scheduled-tasks>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章