有一个自动备份mysql 数据库的需求,windows 下可以写一个bat文件,然后加入到计划任务中设置执行,可是伟大的Windows系统加入计划任务有时间却不执行,而且设置计划任务也挺复杂(写脚本把执行备份的脚本加入计划中)。那就用程序写一个吧备份的功能吧。还是调用备份的脚本,自动任务部分使用Spring3的@Scheduled来实现。
pom.xml文件中依赖的jar:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.5</version>
</dependency>
</dependencies>
spring-config.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="cn.test" />
<task:annotation-driven/>
</beans>
定义一个接口,写一个实现类。
package cn.test;
/**
* Created by libo on 13-12-18.
*/
public interface SchedulerService {
void doSome();
}
package cn.test;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.Calendar;
/**
* Created by libo on 13-12-18.
*/@Component
public class SchedulerServiceImpl
implements SchedulerService {
@Scheduled(cron = "0/5 * * * * ? ")
//每5秒执行一次
@Override
public void doSome() {
System.out.println("do soming
" + Calendar.getInstance().getTime());
Runtime runtime = Runtime.getRuntime();
Process p =
null;
FileWriter fw =
null;
try {
//此处执行的是ipconfig命令,可以换成任何cmd 里的命令。
p = runtime.exec("cmd /c ipconfig /all");
BufferedReader reader =
new BufferedReader(
new InputStreamReader(p.getInputStream(), "GBK"));
// 将命令执行结果保存到文件中
fw =
new FileWriter(
new File("C:/temp/cmdout.txt"));
String line =
null;
while ((line = reader.readLine()) !=
null) {
fw.write(line + "\n");
}
fw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (p !=
null) {
p.destroy();
}
try {
if (fw !=
null)
fw.close();
if (p !=
null)
p.getOutputStream().close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("do soming
" + Calendar.getInstance().getTime());
}
}
测试类(注意:使用junit是不能测试自动任务地!)
package cn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by libo on 13-12-18.
*/public class Test {
public static void main(String[] args){
ApplicationContext context =
new ClassPathXmlApplicationContext("/spring-config.xml");
System.out.println("请等待5秒
让任务飞一会儿!");
}
}
end.
posted on 2013-12-18 16:35
Libo 阅读(792)
评论(0) 编辑 收藏 所属分类:
其他