mysql每日定时备份
小于 1 分钟
使用golang开发一个mysql自动备份的程序,使用docker-composer的方式运行
package main
import (
"fmt"
"os"
"os/exec"
"time"
)
func main() {
// 设置备份的目标数据库信息
dbHost := "localhost"
dbPort := "3306"
dbUser := "your_mysql_username"
dbPassword := "your_mysql_password"
dbName := "your_database_name"
backupPath := "/path/to/backup/directory/" // 设置备份文件存放路径
backupFileName := fmt.Sprintf("%s-%s.sql", dbName, time.Now().Format("2006-01-02"))
// 计算备份执行的时间,每天凌晨备份
now := time.Now()
nextDay := now.Add(24 * time.Hour)
nextMidnight := time.Date(nextDay.Year(), nextDay.Month(), nextDay.Day(), 0, 0, 0, 0, nextDay.Location())
timeToBackup := nextMidnight.Sub(now)
// 使用定时器定时执行备份任务
timer := time.NewTimer(timeToBackup)
<-timer.C // 等待定时器触发
// 构造备份命令
cmd := exec.Command("mysqldump", "-h"+dbHost, "-P"+dbPort, "-u"+dbUser, "-p"+dbPassword, dbName)
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println("Error creating stdout pipe:", err)
return
}
// 执行备份命令
if err := cmd.Start(); err != nil {
fmt.Println("Error starting backup command:", err)
return
}
// 创建备份文件
backupFile, err := os.Create(backupPath + backupFileName)
if err != nil {
fmt.Println("Error creating backup file:", err)
return
}
defer backupFile.Close()
// 将备份数据写入文件
if _, err := io.Copy(backupFile, stdout); err != nil {
fmt.Println("Error writing backup data to file:", err)
return
}
// 等待备份命令执行完毕
if err := cmd.Wait(); err != nil {
fmt.Println("Error waiting for backup command to finish:", err)
return
}
fmt.Println("Backup completed successfully!")
}