spring自带定时器

1、修改spring配置文件applicationContext.xml:

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

         xsi:schemaLocation=“http://www.springframework.org/schema/task  http://www.springframework.org/schema/task/spring-task-3.0.xsd”


 

 <bean class="com.hmnet.common.TaskJob" name="taskJob"></bean> 
 <task:scheduled-tasks>   
 <!-- 
 "0 0/0 * * * ?"  整点调用,就如时间整点报钟一样。
 "0 0/1 * * * ?"  每1分钟调用一次,每几分钟调用改“1”对应的位置就OK啦。
 "10 0/5 * * * ?"  每5分钟之后的10秒时调用。例如:10:00:10 am, 10:05:10 am,10:10:10 am,10:15:10 am........................
 "0 30 10-13 ? * WED,FRI" 在星期三到星期五的10:30, 11:30, 12:30, and 13:30调用。
 "0 0/30 8-9 5,20 * ?"  在每个月的5号和20号,在上午 8:00, 8:30, 9:00 and 9:30会被调用。
  -->
 <task:scheduled ref="taskJob" method="doMyJob" cron="0 0/50 * * * ?"/>   
 </task:scheduled-tasks>  
 <context:component-scan base-package=" com.hmnet.common " /> 


2、新建工作类

package com.hmnet.common;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;


public class TaskJob{ 
	@Autowired
    DataSource dataSource;  
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public void doMyJob(){
			 Connection connection=null;
			try {
				connection = dataSource.getConnection();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			Statement statement=null;
			try {
				String sql = "";
				sql = "update SERIAL_NUMBER t set t.IS_TEMP_BUSY = '0' where t.IS_EMPTY = '0' and t.IS_TEMP_BUSY = '1'";
				statement=connection.createStatement();
				statement.executeUpdate(sql);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					if(null!=statement){
						statement.close();
					}
					if(null!=connection){
						connection.close();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("每隔一段时间,此方法会被调用一次");
	}
}


 

猜你喜欢

转载自blog.csdn.net/xlb744868186/article/details/51074371
今日推荐