使用java的spring定时执行任务

流程:

1.配置web.xml中spring的核心控制器

2.在spring的xml文件中注入定时器,并关联你的逻辑层

3.设置需要执行的时间策略.



第一步:

	<!-- 加载Spring容器配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 设置Spring容器加载所有的配置文件的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:config/spring-*.xml</param-value>
	</context-param>

	<!-- 配置SpringMVC核心控制器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置初始配置化文件,前面contextConfigLocation看情况二选一 -->  
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:config/spring-mvc.xml</param-value>
		</init-param>
		<!-- 启动加载一次 -->  
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!--为DispatcherServlet建立映射 -->
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

第二步:

    <!-- 定时加载的目标类 -->
    <bean id="mytask" class="com.qs.timer.myQuarzt" />
    <!-- 配置定时器详情 -->
    <bean id="mytaskDitail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    	<property name="targetObject" ref="mytask" />
    	<property name="targetMethod" value="doit" />
    </bean>
    <!-- 定义时间间隔触发器 -->
    <bean id="timeTigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    	<property name="mytaskDetail" ref="mytaskDitail" />
    	<property name="cronExpression" value="10 0 0 * * ?" />
    </bean>
    <!-- 启动定时器 -->
    <bean id="startJob" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
    	<property name="triggers">
    		<list>
    			<ref bean="timeTigger" />
    		</list>
    	</property>
    </bean>


目前代码设置的自动执行任务的时间是每天的0点0分10秒


第三步:

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.quartz.JobExecutionException;

import com.qs.service.sportService;

public class myQuarzt {
	
	@Resource
	private xxService xxservice;
	
	public void doit()throws JobExecutionException{
		System.setProperty("user.timezone","GMT+8");
		System.out.println("动态时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		//执行数据库删除冗余数据操作
		int flag = this.xxservice.delExpirationDate();
	}

}

最后执行mybatis.xml执行sql语句成功删除数据


DELETE from table1 where substring(theday, 4)<curdate()          theday时间格式为   周二,2017-10-24   所以要使用截取字符串函数


以上就是spring定时器的简单使用示例.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章