63 lines
2.1 KiB
C#
63 lines
2.1 KiB
C#
using LMS.Tools.TaskScheduler;
|
||
using Quartz;
|
||
namespace LMS.service.Configuration
|
||
{
|
||
public static class QuartzTaskSchedulerConfig
|
||
{
|
||
public static void AddQuartzTaskSchedulerService(this IServiceCollection services)
|
||
{
|
||
// 注册 Quartz 服务
|
||
services.AddQuartz(q =>
|
||
{
|
||
|
||
// 配置作业
|
||
var jobKey = new JobKey("MonthlyTask", "DefaultGroup");
|
||
|
||
// 方法1:通过配置属性设置时区
|
||
// 获取中国时区
|
||
TimeZoneInfo chinaTimeZone;
|
||
try
|
||
{
|
||
// 尝试获取 Windows 时区名称
|
||
chinaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("China Standard Time");
|
||
}
|
||
catch
|
||
{
|
||
try
|
||
{
|
||
// 尝试获取 Linux 时区名称
|
||
chinaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai");
|
||
}
|
||
catch
|
||
{
|
||
// 如果都不可用,使用 UTC+8
|
||
chinaTimeZone = TimeZoneInfo.CreateCustomTimeZone(
|
||
"China_Custom",
|
||
new TimeSpan(8, 0, 0),
|
||
"China Custom Time",
|
||
"China Standard Time");
|
||
}
|
||
}
|
||
|
||
// 添加作业
|
||
q.AddJob<ResetUserFreeCount>(opts => opts.WithIdentity(jobKey));
|
||
|
||
// 添加触发器 - 每月1号凌晨0点执行
|
||
q.AddTrigger(opts => opts
|
||
.ForJob(jobKey)
|
||
.WithIdentity("MonthlyTaskTrigger", "DefaultGroup")
|
||
.WithCronSchedule("0 0 18 24 * ?")); // 每月1号凌晨0点
|
||
});
|
||
|
||
// 添加 Quartz 托管服务
|
||
services.AddQuartzHostedService(options =>
|
||
{
|
||
options.WaitForJobsToComplete = true;
|
||
});
|
||
|
||
// 注册作业
|
||
services.AddTransient<ResetUserFreeCount>();
|
||
}
|
||
}
|
||
}
|