如何在已安装服务的情况下从外部文件更改工人服务间隔时间

问题描述 投票:1回答:1

我正在.NET Core“工人服务”项目中为Windows和Linux OS实施服务。

服务从外部config.xml文件读取数据,例如凭据/ URL。我也想在配置文件中添加间隔时间,以便将来如果我想要更改间隔时间(例如,每小时到每2小时),我将只更新配置文件,而无需修改和重新编译代码。

我正在使用Coraval库进行调度。用interval方法设置Main时间。我的疑问是何时更改配置文件中的interval时间(正在Main方法中读取),如何将其分配给进一步执行?对于WindowsLinux

Main方法多久被调用一次,以便它从配置文件中读取新的调度时间?

这是我的代码

public static void Main(string[] args)
{
    var schedulingConfig = GlobalSettings.ReadIntervals(out List<intervalValue> intervalvalues);
    string intrvaltype = string.Empty;
    foreach (var item in schedulingConfig)
    {
        if (item.Name == "true")
        {
            intrvaltype = item.Execution;
            break;
        }
    }
    IHost host = CreateHostBuilder(args).Build();
    host.Services.UseScheduler(scheduler =>
    {
       //Remind schedular to repeat the same job  
        switch (intrvaltype)
        {
            case "isSignleHourInADay":
                scheduler
               .Schedule<ReprocessInvocable>()
               .Hourly();
                break;
            case "isMinutes":
                scheduler
               .Schedule<ReprocessInvocable>()
               .EveryFiveMinutes();
                break;

            case "isOnceInADay":
                scheduler
               .Schedule<ReprocessInvocable>()
               .Daily();
                break;

            case "isSecond":
                scheduler
               .Schedule<ReprocessInvocable>()
               .EveryThirtySeconds();
                break;
        }  
    });
    host.Run();
}

我应该将代码保存在哪里,以便它可以处理需要的工作?

c# .net asp.net-core .net-core main
1个回答
0
投票

正如我在Coravel中看到的那样,它具有When方法可能是您的解决方案:

首先定义一个方法,该方法根据您的配置说明哪个Interval有效运行:

static Task<bool> IsRun(TimeSpan timeSpan)
{
    return Task.Run(() =>
    {
        GlobalSettings.ReadIntervals(out List<double> intervalMilliseconds);
        // I assumed that intervalMilliseconds is your valid intervals in milliseconds
        return intervalMilliseconds.Contains(timeSpan.TotalMilliseconds);
    });
}

然后以这种方式将When添加到您的Invocables:

host.Services.UseScheduler(scheduler =>
{
    scheduler
    .Schedule<ReprocessInvocable>()
    .Hourly()
    .When(() => IsRun(new TimeSpan(1, 0, 0)));

     scheduler
     .Schedule<ReprocessInvocable>()
     .EveryFiveMinutes()
     .When(() => IsRun(new TimeSpan(0, 5, 0)));

     scheduler
     .Schedule<ReprocessInvocable>()
     .Daily()
     .When(() => IsRun(new TimeSpan(24, 0, 0)));

     scheduler
     .Schedule<ReprocessInvocable>()
     .EveryThirtySeconds()
     .When(() => IsRun(new TimeSpan(0, 0, 30)));
});
© www.soinside.com 2019 - 2024. All rights reserved.