使用spring scheduler完成定时调度

在applicationContext-task.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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd"
	default-autowire="byName">


	
	<task:scheduler id="scheduler" pool-size="10" />
	<task:scheduled-tasks scheduler="scheduler" >
		
		
		<task:scheduled ref="springTask" method="twoMin" cron="0 */2 * * * ?" />
	task:scheduled-tasks>
beans>

将applicationContext-task.xml中的配置引入到web.xml中


	<servlet>
		<servlet-name>DispatcherServletservlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
		
		<load-on-startup>1load-on-startup>
		
		<init-param>
			<param-name>contextConfigLocationparam-name>
			
			<param-value>
				classpath*:META-INF/spring/applicationContext-*.xml,
				classpath*:META-INF/spring/*-applicationContext.xml
			param-value>
		init-param>
	servlet>

测试看能不能执行:

@Component("springTask")
public class SpringTask extends BaseController{
     
	
	
	/**
	 * scheduler
	 * 每两分钟执行一次
	 */
	public void twoMin()
	{
     
		Date date = new Date();
		String dateToStr = this.dateUtil.dateToStr(date, "yyyy-MM-dd HH:mm:ss");
		System.out.println("两分钟执行一次定时任务  "+dateToStr);
	}

}

执行效果:
使用spring scheduler完成定时调度_第1张图片

你可能感兴趣的:(java,spring,java)