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 ------------------------------------");
    }
}

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Spring,你可以使用`@Scheduled`注解来创建定时任务。例如: ``` @Scheduled(fixedRate = 1000) public void reportCurrentTime() { System.out.println("每隔1秒执行一次 " + dateFormat.format(new Date())); } ``` 这个注解可以被放在类的方法上,表示每隔1秒(由`fixedRate`属性指定)就会执行一次这个方法。 此外,你还可以使用`fixedDelay`属性来指定任务执行完成后再过多长时间再执行,或者使用`cron`属性来指定使用Cron表达式来控制任务的执行时间。 你需要在你的Spring配置文件启用定时任务的支持。例如,如果你使用的是XML配置文件,你可以添加如下内容: ``` <task:annotation-driven /> ``` 这样,Spring就会扫描你的应用程序带有`@Scheduled`注解的方法,并自动创建定时任务。 ### 回答2: Spring定时任务是指通过Spring框架提供的功能,在特定的时间间隔或固定的时间点执行某个任务或方法。Spring框架为定时任务提供了多种实现方式,如通过注解和XML配置等。 使用注解方式实现定时任务:首先,在配置类加入@EnableScheduling注解开启定时任务的支持,然后在需要定时执行的方法上加入@Scheduled注解,并指定触发的时间间隔或时间点。例如,@Scheduled(fixedDelay=5000)表示每隔5秒执行一次方法。 使用XML配置方式实现定时任务:在XML配置文件加入<task:annotation-driven/>来启用定时任务的支持,然后在需要定时执行的方法上加入<task:scheduled>标签,并指定触发的时间间隔或时间点。例如,<task:scheduled fixedDelay="5000"/>表示每隔5秒执行一次方法。 定时任务的执行可以在不同的线程进行,可以通过配置来控制线程池的大小和其他相关参数。定时任务还可以设置初始延迟时间、指定固定的执行时间、cron表达式等功能,以满足不同的业务需求。 在定时任务执行过程,如果任务方法抛出异常,则Spring会捕获并记录异常信息,但不会断整个应用的运行。定时任务一般是单例模式的,因此需要注意线程安全问题。 总之,Spring定时任务功能提供了便捷的方式来执行周期性任务或在指定时间执行任务,能够帮助开发人员实现定时调度等特定需求。无论是通过注解还是XML配置,都可以方便地配置定时任务的执行方式和时间规则。 ### 回答3: Spring定时任务是指通过Spring框架提供的定时任务功能来执行一些指定的任务。Spring框架提供了多种方式来实现定时任务,包括使用注解、接口、XML配置等。 其最常用的方式是通过使用注解来实现定时任务。通过在需要定时执行的方法上添加@Scheduled注解,可以指定方法的执行间隔、定时时机、循环次数等属性。例如,可以使用@Scheduled(cron="0 0 0 * * ?")来指定每天的午夜零点执行任务。 除了注解方式,还可以通过实现SchedulingConfigurer接口来自定义定时任务的执行策略。该接口定义了configureTasks方法,可以在这里配置任务的触发器、执行器等。使用这种方式可以更加灵活地定制任务的执行方式。 另外,Spring框架还支持使用XML配置的方式来实现定时任务。通过在配置文件定义<task:scheduled-tasks>和<task:scheduler>标签可以配置定时任务的执行方式和时间。这种方式适用于一些较为复杂的定时任务场景。 总的来说,Spring定时任务功能非常强大且灵活,可以满足各种定时任务的需求。无论是简单的定时执行,还是复杂的周期性任务,都可以通过Spring框架来实现。使用Spring定时任务功能可以简化开发,提高代码的可维护性和可测试性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值