worker service配置服务,quartz托管

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 * * * * ?"
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值