第一步 :添加mysqldump.exe 进环境变量
第二步 新建一个spring boot 项目,连接数据库
spring.datasource.url=jdbc:mysql://localhost:3308/springbootdb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
第三步 添加相关需要的jar
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-quartz
第四步 创建定时任务
/*** 执行定时任务*/@Overrideprotected void executeInternal(JobExecutionContext context) throwsJobExecutionException {//TODO Auto-generated method stub
System.out.println("执行定时任务》》》"+newDate());
String filePath="D:\\数据库文件\\";
String dbName="springbootdb";//备份的数据库名
String username="root";//用户名
String password="mysql";//密码
File uploadDir = newFile(filePath);if (!uploadDir.exists())
uploadDir.mkdirs();
String cmd= "mysqldump -u"+ username +" -p "+password + dbName + " -r "
+ filePath + "/" + dbName+new java.util.Date().getTime()+ ".sql";try{
Process process=Runtime.getRuntime().exec(cmd);
System.out.println("备份数据库成功!!!");
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
第五步 配置quartz,设置每10秒执行一次定时任务
@Configurationpublic classQuartzConfig {
@BeanpublicJobDetail teatQuartzDetail(){return JobBuilder.newJob(TestQuartz.class).withIdentity("testQuartz").storeDurably().build();
}
@BeanpublicTrigger testQuartzTrigger(){
SimpleScheduleBuilder scheduleBuilder=SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10) //设置时间周期单位秒
.repeatForever();returnTriggerBuilder.newTrigger().forJob(teatQuartzDetail())
.withIdentity("testQuartz")
.withSchedule(scheduleBuilder)
.build();
}
}
第六步 运行项目
备份成功!!!!!!!!!!!!!!!!!!!!