Spring中定时任务

    需求:每天上午9点运行任务

    使用Spring框架实现定时任务的编写,这里有两种方法.

     一timer定时器

public class TestListen implements ServletContextListener {
	
	private Timer timer = null;
	//时间间隔(一天)  
	private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("task stop...............");
		timer.cancel();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("task statr.............");
		Calendar calendar = Calendar.getInstance();  
	    calendar.set(Calendar.HOUR_OF_DAY, 9); //每天9点  
	    calendar.set(Calendar.MINUTE, 0);  
	    calendar.set(Calendar.SECOND, 0);  
	    Date date=calendar.getTime(); //第一次执行定时任务的时间  
	    //如果第一次执行定时任务的时间 小于当前的时间  
	    //此时要在 第一次执行定时任务的时间加一天,以便此任务在下个时间点执行。如果不加一天,任务会立即执行。  
	    if (date.before(new Date())) {  
	        date = this.addDay(date, 1);  
	    }  
	    timer = new Timer(true);
	    //安排指定的任务在指定的时间开始进行重复的固定延迟执行。  
	    timer.schedule(new TestTask(),date,PERIOD_DAY);
	}
	
	// 增加或减少天数  
	public Date addDay(Date date, int num) {  
	    Calendar startDT = Calendar.getInstance();  
	    startDT.setTime(date);  
	    startDT.add(Calendar.DAY_OF_MONTH, num);  
	    return startDT.getTime();  
	}  
}
public class TestTask extends TimerTask {
	@Override
	public void run() {
		System.out.println("这是定时任务==============================="+new Date().getSeconds());

	}

}

    具体步骤:

    1.一个TestListen继承 ServletContextListener,重写 contextInitialized()方法,项目启动时,调用 contextInitialized()方法.

    2.在contextInitialized()方法中使用 timer.schedule(new TestTask(),date,PERIOD_DAY) 按规定时间 调用具体任务类TestTask.

    3. TFPTask 继承 TimerTask 重写 run() 方法, 定时任务具体的代码 在 run() 方法里.

参考文章:

点击打开链接

    二、Spring 整合Quartz框架

在Spring 的配置文件 quartz-task.xml 中 配置:

 <bean id="resetPidTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
     <description>每天日重置线程池运行任务</description>
		<property name="jobDetail">
	    <bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
	<!-- 	调用的具体类 -->
                     <bean class="com.cares.ceseas.service.timetask.SendEmailForCard" />
	         </property>
	<!-- 	调用的具体类中的方法 run() -->
	         <property name="targetMethod"><value>run</value></property>
	    </bean>
	</property>
	<property name="cronExpression">
<!-- 	    <value>0 0 9 * * ?</value> -->
<!-- 		每10秒执行一次 -->
<!-- 	    <value>0/10 * * * * ?</value> -->
	    <value>0 */1 * * * ?</value>
	 </property>
  </bean>
	 
  <bean id="schedulerFactory" autowire="no"
	class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<description>定时触发器 设置</description>
	    <property name="triggers">
	        <list>
	           <ref local="resetPidTrigger"/> 
	        </list>
	    </property>
   </bean> 
public class SendEmailForCard {
		
	public void run() {
        	System.out.println("Quartz的任务调度!!!发送邮件-=====--==="+new Date().getSeconds());
	}
}

参考文章:

点击打开链接

 

执行多个定时任务

一 、使用 ScheduledExecutorService 并发包,开启多个线程执行 多个定时任务

public class SummaryListen implements ServletContextListener {
	/**
	 * 使用工厂方法初始化一个ScheduledThreadPool
	 */
	ScheduledExecutorService newScheduledThreadPool = Executors
			.newScheduledThreadPool(10);
	Logger logger = Logger.getLogger(SummaryListen.class.getName());

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		newScheduledThreadPool.shutdown();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
        
		Future<?>f1 = newScheduledThreadPool.scheduleAtFixedRate(
				new Task1(), 0, 15, TimeUnit.MINUTES);
		Future<?>f2 = newScheduledThreadPool.scheduleAtFixedRate(
				new Task2(), 0, 24, TimeUnit.HOURS);
		Future<?>f3 = newScheduledThreadPool.scheduleAtFixedRate(
                    new Task3(),0, 5, TimeUnit.MINUTES);
		Future<?>f4 = newScheduledThreadPool.scheduleAtFixedRate(
                    new Task4(),0, 10, TimeUnit.MINUTES);
                ......
		try {
			f1.get();
			f2.get();
			f3.get();
			f4.get();
			......
		} catch (InterruptedException e) {
			logger.error(e.getMessage(), e);
		} catch (ExecutionException e) {
			logger.error(e.getMessage(), e);
		}
	}

}
public class Task1 extends TimerTask {
	Logger logger = Logger.getLogger(Task1.class.getName());

	@Override
	public void run() {
		logger.info("*** Task1 START!! *****************");
		......
	}
}

、Spring 整合Quartz框架,quartz-task.xml配置多个 Job

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
	default-lazy-init="false">
<!-- 线程池 -->
	<bean id="executor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> 
		<property name="corePoolSize" value="10" /> 
		<property name="maxPoolSize" value="100" /> 
		<property name="queueCapacity" value="500" />
	</bean>
	<!--每日任务 -->
<!-- Job1 -->
	<bean id="job1" class="com.care.service.Job1"></bean>
	<bean id="Job1Detail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="job1" />
		<property name="targetMethod" value="execute" />
	</bean>
<!-- 调度器1 -->
	<bean id="Job1Trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="Job1Detail" />
		<property name="cronExpression" value="0/11 * * * * ?" />
	</bean>
<!-- Job2 -->
	<bean id="job2" class="com.care.service.Job2"></bean>
	<bean id="Job2Detail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="job2" />
		<property name="targetMethod" value="execute" />
	</bean>
	<bean id="Job2Trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="Job2Detail" />
		<property name="cronExpression" value="0/21 * * * * ?" />
	</bean>
	
<!-- 启动触发器的配置 -->
    <bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
       <!-- 通过applicationContextSchedulerContextKey属性配置spring上下文 -->    
        <property name="applicationContextSchedulerContextKey">    
            <value>applicationContext</value>    
        </property>   
        <property name="triggers">  
			<list>   
				<ref bean="Job1Trigger" /> 
				<ref bean="Job2Trigger" />   
			</list> 
		</property> 
    	<property name="taskExecutor" ref="executor" /> 
   	</bean> 
</beans>

在Spring核心配置文件application.xml 导入定时任务的配置文件

<import resource="quartz-task.xml" />

、Quartz注解

在Spring核心配置文件application.xml 配置

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
......
  
<!-- 定时任务 注解方式-->
<task:scheduler id="tmTaskScheduler" pool-size="1"/>
<task:annotation-driven scheduler="tmTaskScheduler" mode="proxy"/>

......
@Service
public class Job1 {
	
@Scheduled(cron="0/10 * * * * ? ")
public void execute(){
	System.out.println("定时任务 1 ------------------------------------");
    }
}
@Service
public class Job2 {
	
@Scheduled(cron="0/10 * * * * ? ")
public void execute(){
	System.out.println("定时任务 2 ------------------------------------");
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值