Spring整合Quartz定时备份数据库
Quartz调度器为调度工作提供了更很好的支持。和Java定时器一样,可以使用Quartz每隔一段时间或在特定的时间点来执行一个任务,Spring作为一个优秀的框架,也提供了对Quartz的整合,下面以我以前做过的项目为例,使用spring的Quartz来定时备份数据库。
数据库的相关信息配置在confin.properties文件中,配置如下:
user=rootpassword=111databasePath=D:/upload/backDatabase/database=erp
/** * 读取properties文件的工具类 * @since 2011-10-5 * @author Jenhui * */public class PropertiesReader { private String fileName; public PropertiesReader(String fileName){ this.fileName=fileName; } public String readProperty(String name){Resource res=new ClassPathResource(fileName);Properties p=new Properties();try{p.load(res.getInputStream());//System.out.println(p.getProperty(name));}catch(Exception e){e.printStackTrace();}return p.getProperty(name);}}
package com.lrh.utils;import java.io.*; import java.text.DateFormat;import java.util.Calendar;import java.util.Date;public class BackMySql { public static void exportDataBase(){ Date now = new Date(); DateFormat df= DateFormat.getDateTimeInstance(); String dbName = df.format(now)+".sql"; dbName=dbName.replaceAll(":", "_"); PropertiesReader pr=new PropertiesReader("config.properties"); String user = pr.readProperty("user"); String password = pr.readProperty("password"); String database = pr.readProperty("database"); String filepath = pr.readProperty("databasePath")+dbName; //System.out.println(filepath); String stmt1 = "mysqldump -u "+user+" -p"+password+" --set-charset=utf8 "+database; try{ Process process = Runtime.getRuntime().exec(stmt1); InputStream in = process.getInputStream(); InputStreamReader xx = new InputStreamReader(in, "utf8"); String inStr; StringBuffer sb = new StringBuffer(""); String outStr; BufferedReader br = new BufferedReader(xx); while ((inStr = br.readLine()) != null) { sb.append(inStr + "\r\n"); } outStr = sb.toString(); FileOutputStream fout = new FileOutputStream(filepath); OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8"); writer.write(outStr); writer.flush(); in.close(); xx.close(); br.close(); writer.close(); fout.close(); }catch(IOException e){ e.printStackTrace(); } } }
public class TriggerImpl {public void BackMySQL(){ BackMySql.exportDataBase();}}
<bean id="trigger" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="timecard2"/> </list> </property> </bean>