This commit is contained in:
wanghu
2026-09-02 10:23:24 +08:00
parent 5a414b14d2
commit ce436cbb32
117 changed files with 13768 additions and 0 deletions
+75
View File
@@ -0,0 +1,75 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using YhCore.Tasks.Jobs;
namespace YhCore.Tasks
{
/// <summary>
/// Quartz 调度宿主(对应 Java scheduler 包由 Spring 管理的调度器)。
/// 承载框架内置 Job 模板;业务 Job 在 InitJobs 中追加注册。
/// </summary>
public class QuartzHostedService : IHostedService
{
private const string ServiceProviderKey = "services";
private readonly ISchedulerFactory _schedulerFactory;
private readonly IServiceProvider _serviceProvider;
private IScheduler _scheduler;
public QuartzHostedService(ISchedulerFactory schedulerFactory, IServiceProvider serviceProvider)
{
_schedulerFactory = schedulerFactory;
_serviceProvider = serviceProvider;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
_scheduler.Context.Put(ServiceProviderKey, _serviceProvider); // Job 经此取 DI 服务
await InitJobs();
await _scheduler.Start(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_scheduler != null)
{
await _scheduler.Shutdown(waitForJobsToComplete: true, cancellationToken);
}
}
private async Task InitJobs()
{
// ============ 定时任务注册 ============
// 1. 审计日志清理(对应 Java SysOperationLogCleanupTask:每日凌晨 3:30 删除 30 天前 sys_operation_log 数据)
await ScheduleJobAsync<CleanupLogJob>("cleanup-log-job", "0 30 3 * * ?");
// 2. 其他业务 Job 在此追加注册(示例:每 10 分钟执行一次)
// await ScheduleJobAsync<TJob>("job-name", "0 */10 * * * ?");
await Task.CompletedTask;
}
/// <summary>注册一个 Cron 定时任务</summary>
protected async Task ScheduleJobAsync<TJob>(string jobName, string cronExpression) where TJob : IJob
{
var job = JobBuilder.Create<TJob>()
.WithIdentity(jobName)
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity(jobName + "-trigger")
.WithCronSchedule(cronExpression)
.Build();
await _scheduler.ScheduleJob(job, trigger);
}
}
}