- 在项目启动类上添加注解 开启定时任务
@EnableScheduling
- 编写定时任务类
sqlUrl 这个的值如果没有配置环境mysql环境变量 需要指定到mysql的安装目录上去执行
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Component
public class Backups {
public static void main(String[] args) throws IOException {
exportDatabaseTool();
}
@Scheduled(cron = "0/30 * * * * ? ")
public static void exportDatabaseTool() throws IOException {
System.out.println("定时备份任务开始执行....>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
String ip = "localhost";
String host = "3306";
String userName = "root";
String password = "root";
String databaseName = "project";
String savePath = "D:\\备份";
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy年MM月dd日HH时mm分ss秒sss" );
String fileName = "project"+sdf.format(new Date())+".sql";
File saveFile = new File(savePath);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
if(!savePath.endsWith(File.separator)){
savePath = savePath + File.separator;
}
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
try {
printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath + fileName), "utf8"));
String sqlUrl = "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump -h" + ip + " -P" + host + " -u" + userName + " -p" + password + " --default-character-set=utf8 " + databaseName;
System.out.println(sqlUrl);
Process process = Runtime.getRuntime().exec(sqlUrl);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
String line;
while((line = bufferedReader.readLine())!= null){
printWriter.println(line);
}
printWriter.flush();
List<File> fileList = Arrays.asList(saveFile.listFiles());
if (fileList.size() >=61){
fileList.get(0).delete();
}
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}