worker设置为windows服务
引入nuget包Microsoft.Extensions.Hosting.WindowsServices
代码
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
发布后直接以管理员身份运行命令行:
sc.exe create NETCoreWorkerService binPath=D:\xxx\xxx\WorkerService.exe
使用quartz托管worker
引入nuget包Quartz.Extensions.Hosting
创建Job:
using Microsoft.Extensions.Logging;
using Quartz;
using System.Threading.Tasks;
[DisallowConcurrentExecution]
public class WorkerJob : IJob
{
private readonly ILogger<WorkerJob> _logger;
public WorkerJob(ILogger<WorkerJob> logger)
{
_logger = logger;
}
public Task Execute(IJobExecutionContext context)
{
_logger.LogInformation("Hello world!");
return Task.CompletedTask;
}
}
配置:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionScopedJobFactory();
// Create a "key" for the job
var jobKey = new JobKey("WorkerJob");
// Register the job with the DI container
q.AddJob<WorkerJob>(opts => opts.WithIdentity(jobKey));
// Create a trigger for the job
q.AddTrigger(opts => opts
.ForJob(jobKey) // link to the WorkerJob
.WithIdentity("WorkerJob-trigger") // give the trigger a unique name
.WithCronSchedule("0/5 * * * * ?")); // run every 5 seconds
});
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
// ...
});
扩展
新增扩展:
public static class ServiceCollectionQuartzConfiguratorExtensions{
public static void AddJobAndTrigger<T>(
this IServiceCollectionQuartzConfigurator quartz,
IConfiguration config)
where T : IJob
{
// Use the name of the IJob as the appsettings.json key
string jobName = typeof(T).Name;
// Try and load the schedule from configuration
var configKey = $"Quartz:{jobName}";
var cronSchedule = config[configKey];
// Some minor validation
if (string.IsNullOrEmpty(cronSchedule))
{
throw new Exception($"No Quartz.NET Cron schedule found for job in configuration at {configKey}");
}
// register the job as before
var jobKey = new JobKey(jobName);
quartz.AddJob<T>(opts => opts.WithIdentity(jobKey));
quartz.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity(jobName + "-trigger")
.WithCronSchedule(cronSchedule)); // use the schedule from configuration
}
}
使用扩展:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionScopedJobFactory();
// Register the job, loading the schedule from configuration
q.AddJobAndTrigger<WorkerJob>(hostContext.Configuration);
});
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
});
配置:
{
"Quartz": {
"WorkerJob": "0/5 * * * * ?"
}
}