gpt4 book ai didi

c# - 已安装服务后如何从外部文件更改工作器服务间隔时间

转载 作者:行者123 更新时间:2023-12-04 15:28:15 25 4
gpt4 key购买 nike

我正在处理 .NET Core 'Worker Service' 项目,用于为 Windows 和 Linux 操作系统实现服务。

服务从外部读取数据 config.xml文件,如凭据/网址。我也想在配置文件中添加间隔时间,以便将来如果我想更改间隔时间(例如每小时到每 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();
}

我应该在哪里保存我的代码,以便它可以做需要的事情?

编辑 1
Program.cs类(class)
public class Program
{
public static void Main(string[] args)
{
IHost host = CreateHostBuilder(args).Build();
host.Services.UseScheduler(scheduler =>
{
scheduler
.Schedule<ReprocessInvocable>()
.Hourly()
.When(() => IsRun("isSignleHourInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EveryFiveMinutes()
.When(() => IsRun("isMinutes"));

scheduler
.Schedule<ReprocessInvocable>()
.Daily()
.When(() => IsRun("isOnceInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EveryThirtySeconds()
.When(() => IsRun("isSecond"));

});
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddScheduler();
}).UseSerilog().UseSystemd();

static Task<bool> IsRun(string intervalType)
{
return Task.Run(() =>
{
var schedulingConfig = ConfigData();
string configIntrvalType = schedulingConfig.FirstOrDefault(i => i.Name == "true")?.Execution;
return intervalType == configIntrvalType;
});
}

public static List<intervalValue> ConfigData()
{
return new List<intervalValue> { new intervalValue { Execution= "isSignleHourInADay", Name="false"},
new intervalValue { Execution= "isMinutes", Name="true"},
new intervalValue { Execution= "isOnceInADay", Name="false"},
new intervalValue { Execution= "isSecond", Name="false"},
new intervalValue { Execution= "isMultipleHoursInADay", Name="false"},
};
}
public class intervalValue
{
public string Execution { get; set; }
public string Name { get; set; }
}
}
ReprocessInvocable.cs类(class)
public class ReprocessInvocable : IInvocable
{
private readonly ILogger<ReprocessInvocable> _logger;
public ReprocessInvocable(ILogger<ReprocessInvocable> logger)
{
_logger = logger;
}
public async Task Invoke()
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
Log.Information("Invoke has called at: {time}", DateTimeOffset.Now);
}
}

编辑 2
这是 StatusConfigTest2.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<parameters>
<intervalValue>
<Definition Execution="isMultipleHoursInADayVal" Name="1AM,4PM,6AM"></Definition>
<Definition Execution="isSignleHourInADayVal" Name="4AM"></Definition>
<Definition Execution="isMinutesVal" Name="5"></Definition>
<Definition Execution="isOnceInADayVal" Name="5PM"></Definition>
<Definition Execution="isSecondVal" Name="20"></Definition>
</intervalValue>
<intervalType>
<Definition Execution="isMultipleHoursInADay" Name="false"></Definition>
<Definition Execution="isSignleHourInADay" Name="false"></Definition>
<Definition Execution="isMinutes" Name="true"></Definition>
<Definition Execution="isOnceInADay" Name="false"></Definition>
<Definition Execution="isSecond" Name="false"></Definition>
</intervalType>
</parameters>

读取xml文件的方法
public static List<intervalValue> GetFilterProducts1(out List<intervalValue> 
intervalValueout)
{
List<intervalValue> IntrvalValueList = new List<intervalValue>();
List<intervalValue> IntervalTypeList = new List<intervalValue>();

try
{
FileStream fs = null;
var files = new List<string>();
files.Add("D:/ProductStatusConfigTest2.xml");
//file2
//file3
foreach (var file in files)
{
try
{
fs = new FileStream(file, FileMode.Open, FileAccess.Read);
break;
}
catch (Exception ex)
{
//throw;
}
}

XmlDocument doc = new XmlDocument();
doc.Load(fs);
XmlNode node = doc.DocumentElement.SelectSingleNode("/parameters/intervalValue");
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IntrvalValueList.Add(new intervalValue { Name = node.ChildNodes[i].Attributes["Name"].Value, Execution = node.ChildNodes[i].Attributes["Execution"].Value });
}
}
XmlNode node2 = doc.DocumentElement.SelectSingleNode("/parameters/intervalType");
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IntervalTypeList.Add(new intervalValue { Name = node2.ChildNodes[i].Attributes["Name"].Value, Execution = node2.ChildNodes[i].Attributes["Execution"].Value });
}
}
intervalValueout = IntrvalValueList;
return IntervalTypeList;
}
catch (Exception ex)
{
intervalValueout = IntervalTypeList;
return IntervalTypeList;
}
}

最佳答案

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

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

static Task<bool> IsRun(string intervalType)
{
return Task.Run(() =>
{
var schedulingConfig = GlobalSettings.ReadIntervals(out List<intervalValue> intervalvalues);
string configIntrvalType = schedulingConfig.FirstOrDefault(i => i.Name == "true")?.Execution;
return intervalType == configIntrvalType;
});
}

然后添加 When以这种方式到您的 Invocables:
host.Services.UseScheduler(scheduler =>
{
scheduler
.Schedule<ReprocessInvocable>()
.Hourly()
.When(() => IsRun("isSignleHourInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EveryFiveMinutes()
.When(() => IsRun("isMinutes"));

scheduler
.Schedule<ReprocessInvocable>()
.Daily()
.When(() => IsRun("isOnceInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EveryThirtySeconds()
.When(() => IsRun("isSecond"));
});

编辑

这是应该可以工作的完整代码:

Program.cs
public class Program
{
public static void Main(string[] args)
{
IHost host = CreateHostBuilder(args).Build();
host.Services.UseScheduler(scheduler =>
{
scheduler
.Schedule<ReprocessInvocable>()
.Hourly()
.When(() => IsRun("isSignleHourInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EveryMinute()
.When(() => IsRun("isMinutes"));

scheduler
.Schedule<ReprocessInvocable>()
.Daily()
.When(() => IsRun("isOnceInADay"));

scheduler
.Schedule<ReprocessInvocable>()
.EverySecond()
.When(() => IsRun("isSecond"));

});
host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddScoped<ReprocessInvocable>();
services.AddScheduler();
});

static Task<bool> IsRun(string intervalType)
{
return Task.Run(() =>
{
var schedulingConfig = GetFilterProducts(out List<intervalValue> intrvalValueList);
string configIntrvalType = schedulingConfig.FirstOrDefault(i => i.Name.ToLower().Trim() == "true")?.Execution;
return intervalType.ToLower().Trim() == configIntrvalType.ToLower().Trim();
});
}

static List<intervalValue> GetFilterProducts(out List<intervalValue> intervalValueList)
{
List<intervalValue> IntervalTypeList = new List<intervalValue>();
intervalValueList = new List<intervalValue>();

try
{
XmlDocument doc = new XmlDocument();
doc.Load("D:/ProductStatusConfigTest2.xml");
XmlNode node = doc.DocumentElement.SelectSingleNode("/parameters/intervalValue");
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
intervalValueList.Add(new intervalValue { Name = node.ChildNodes[i].Attributes["Name"].Value, Execution = node.ChildNodes[i].Attributes["Execution"].Value });
}
}
XmlNode node2 = doc.DocumentElement.SelectSingleNode("/parameters/intervalType");
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IntervalTypeList.Add(new intervalValue { Name = node2.ChildNodes[i].Attributes["Name"].Value, Execution = node2.ChildNodes[i].Attributes["Execution"].Value });
}
}
return IntervalTypeList;
}
catch (Exception ex)
{
intervalValueList = IntervalTypeList;
return IntervalTypeList;
}
}

class intervalValue
{
public string Execution { get; set; }
public string Name { get; set; }
}
}

ReprocessInvocable.cs
public class ReprocessInvocable : IInvocable
{
private readonly ILogger<ReprocessInvocable> _logger;
public ReprocessInvocable(ILogger<ReprocessInvocable> logger)
{
_logger = logger;
}
public async Task Invoke()
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.CompletedTask;
}
}

关于c# - 已安装服务后如何从外部文件更改工作器服务间隔时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61817527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com