定时任务

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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值