java 执行批处理文件.bat 数据库自动备份

来源:互联网 发布:淘宝上买精密管犯法吗? 编辑:程序博客网 时间:2024/05/07 21:02

1.提前写好备份.bat,放在某个文件夹里,将路径设置在.properties里的

 @echo off
set txt=%date:~0,4%%date:~5,2%%date:~8,2%%time:~0,2%%time:~3,2%%time:~6,2%
echo %txt%
echo --------------------------------------------------
echo -------------正在执行oracle数据库备份--------------
echo --------------------------------------------
echo ...
echo ...
echo 导出Database...
if exist %txt%.dmp del %txt%.dmp
exp userid=user/user@ORCL file=d:/%txt%.dmp
echo ...
echo ...
echo 备份完成!

exit

 

2.在XML文件里添加监听
<listener>
 <listener-class>
  com.dbbackup.DbBackUpListener 
 </listener-class>
</listener>

 

3.主程序

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;


public class DbBackUpListener implements ServletContextListener {

 

// 设置备份间隔时间
 int intTime = 60;//这里设置1分钟执行一次

 public void contextDestroyed(ServletContextEvent sce) {
 }

 public void contextInitialized(ServletContextEvent sce) {
  ServletContext ctx = sce.getServletContext();

  

// 取得.bat文件的路径。路径设置到了.properties里
  String filePath = PropertyUtil
    .getProperty("WEB-INF/test.bat");

  PickTask picktask = new PickTask(ctx.getRealPath(filePath));

  

// 多久执行一次
  picktask.start(1, intTime);
 }
}

 


class PickTask {
     private Timer timer;
     private String fileName = null;

     public PickTask(String fileName1) {
          this.timer = new Timer();
          this.fileName = fileName1;
     }

 private TimerTask task = new TimerTask() {
    public void run() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginDate = sdf.format(date);
        String beginYear = beginDate.substring(0, 4);// 年
        String beginMonth = beginDate.substring(5, 7);// 月
        String beginDay = beginDate.substring(8, 10);// 日
        String beginTime = beginDate.substring(11, 16);// 分:秒

   

    if (beginTime.equals(23:30)) && beginDay.equals("16")) { // 根据具体情况设置条件,这里执行条件为每月16日,23:30
         try {

              Runtime rt = Runtime.getRuntime();
              rt.exec("cmd.exe /C start "+fileName );
        } catch (FileNotFoundException e) {
              System.out.println("can not find the file");
        } catch (IOException e) {
               e.printStackTrace();
      }
   }
  }
 };

 public void start(int delay, int internal) {
      timer.schedule(task, delay * 1000, internal * 1000);
 }
}

原创粉丝点击