1
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 23s
Docker Build & Deploy / Deploy to Production (push) Successful in 6s
Docker Build & Deploy / Cleanup Dangling Images (push) Successful in 1s
Docker Build & Deploy / WeChat Notification (push) Successful in 1s
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 23s
Docker Build & Deploy / Deploy to Production (push) Successful in 6s
Docker Build & Deploy / Cleanup Dangling Images (push) Successful in 1s
Docker Build & Deploy / WeChat Notification (push) Successful in 1s
This commit is contained in:
70
Service/Jobs/DbBackupJob.cs
Normal file
70
Service/Jobs/DbBackupJob.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Quartz;
|
||||
|
||||
namespace Service.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// 数据库备份任务
|
||||
/// </summary>
|
||||
public class DbBackupJob(
|
||||
IHostEnvironment env,
|
||||
ILogger<DbBackupJob> logger) : IJob
|
||||
{
|
||||
public Task Execute(IJobExecutionContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("开始执行数据库备份任务");
|
||||
|
||||
// 数据库文件路径 (基于 appsettings.json 中的配置: database/EmailBill.db)
|
||||
var dbPath = Path.Combine(env.ContentRootPath, "database", "EmailBill.db");
|
||||
var backupDir = Path.Combine(env.ContentRootPath, "database", "backups");
|
||||
|
||||
if (!File.Exists(dbPath))
|
||||
{
|
||||
logger.LogWarning("数据库文件不存在,跳过备份: {Path}", dbPath);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(backupDir))
|
||||
{
|
||||
Directory.CreateDirectory(backupDir);
|
||||
}
|
||||
|
||||
// 创建备份
|
||||
var backupFileName = $"EmailBill_backup_{DateTime.Now:yyyyMMdd}.db";
|
||||
var backupPath = Path.Combine(backupDir, backupFileName);
|
||||
|
||||
File.Copy(dbPath, backupPath, true);
|
||||
logger.LogInformation("数据库备份成功: {Path}", backupPath);
|
||||
|
||||
// 清理旧备份 (保留最近20个)
|
||||
var files = new DirectoryInfo(backupDir).GetFiles("EmailBill_backup_*.db")
|
||||
.OrderByDescending(f => f.LastWriteTime) // 使用 LastWriteTime 排序
|
||||
.ToList();
|
||||
|
||||
if (files.Count > 20)
|
||||
{
|
||||
var filesToDelete = files.Skip(20);
|
||||
foreach (var file in filesToDelete)
|
||||
{
|
||||
try
|
||||
{
|
||||
file.Delete();
|
||||
logger.LogInformation("删除过期备份: {Name}", file.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "删除过期备份失败: {Name}", file.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "数据库备份任务执行失败");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user