web开发中定时器配置及定时任务执行

一、 JavaWeb项目中java自带的定时器Timer

1.java代码

package com.timer.task;
 
	import java.util.Timer;
	import java.util.TimerTask;
	import java.util.Date; 
 
	import javax.servlet.ServletContextEvent;
	import javax.servlet.ServletContextListener;
 
	public class MyTimerTask implements ServletContextListener{
		private Timer timer;
		@Override
		public void contextDestroyed(ServletContextEvent arg0) {
			if(timer!=null) timer.cancel();
		}
 
		@Override
		public void contextInitialized(ServletContextEvent arg0) {
			timer = new Timer();
			timer.schedule(new TimerTask() {
				
				@Override
				public void run() {
					work();
				}
			}, 1000, 15*1000);// 一秒后执行,间隔十五秒执行一次。
		}
		
		private void work() {
			System.out.println("定时任务...." + new Date());
		}
	}

2.在web.xml中配置监听

	<listener>
		
		<listener-class>com.timer.task.MyTimerTasklistener-class>
	listener>

二、JavaWeb项目中Spring自带的定时任务的使用简介(非注解形式)

1.java代码

		package com.timer.task;
		
		import java.util.Date; 
		
		public class MyTask {
			public void task(){
				System.out.println("定时任务..." + new Date());
			}
		}

2.applicationContext.xml

		<bean id="myTask" class="com.sundy.task.MyTask">bean>
		<task:scheduled-tasks> 
			
			<task:scheduled ref="myTask" method="task" cron="*/5 * * * * ?"/> 
		task:scheduled-tasks> 

ps:在项目中添加task标签时可能会遇到The perfix "task" for element "task:excutor" is not bound.是因为在xml头部没有定义

xmlns:task="http://www.springframework.org/schema/task"

http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd

3.web.xml

	
	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:applicationContext.xmlparam-value>
	context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>

三、JavaWeb项目中Spring自带的定时任务的使用简介(注解形式)

1.java代码

	package com.timer.task;
 
 	import java.util.Date;
	import org.springframework.scheduling.annotation.Scheduled;
	import org.springframework.stereotype.Component;
	
 
	@Component
	public class MyTask {
		// 每隔5秒执行一次
		@Scheduled(cron="*/5 * * * * ?")
		public void task(){
			System.out.println("定时任务..." + new Date());
		}
	}

2.applicationContext.xml

	<context:component-scan base-package="com.tiemr.task"/>
	  
    <task:executor id="executor" pool-size="10" />  
    <task:scheduler id="scheduler" pool-size="10" />  
	<task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>

ps: 1. 如果项目中本来就有标签时,再添加扫描包只需要在base-package里面用,连接即可;
2. 如果启动服务,报错aop/advance之类的错是因为没有动态注解的包,需要下载aopalliance-1.0,即可。

你可能感兴趣的:(工具)