先是增添二个.json 文件

率先增添二个.json 文件,例如 setting.json
文件内容如下,记得把公文设置为“复制到输出目录”

{
“ConfigSetting”: {
“XXXName”: “Name”,
“XXXValue”: “Value”
}
}

 

下来定义三个收受Model 

public class SettingModel
{
public string XXXName { get; set; }

public string XXXValue { get; set; }
}

在 Startup.cs 的主意中 public void ConfigureServices(IServiceCollection
services) 增多下边包车型客车登记事件

 services.Configure<SettingModel>(Configuration.GetSection(“ConfigSetting”));

 

下一场在职分Controller 只怕是服务中就会健康使用,使用格局见上边深褐部分:

public class SyncService : IBaseService
{

private readonly System.Timers.Timer _timer;
private readonly ILogger logger;
private readonly SettingModel settingModel;
public SyncService(IOptions<SettingModel>
settingOptons, ILoggerFactory loggerFactory)
{
this.settingModel = settingOptons.Value;
_timer = new System.Timers.Timer(10000);
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

_timer.Interval = 2000;

_timer.AutoReset = true;
_timer.Enabled = false;
logger = loggerFactory.CreateLogger<SyncService>();
}

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine(string.Format(“SyncService:{0:yyyy-MM-dd HH:mm:sss}”,
DateTime.Now));
_timer.Enabled = false;

try
{
//do some job;
}
catch (Exception ex)
{
logger.LogError(“SyncService Error {0}:”, ex.Message);
}
Console.WriteLine(string.Format(“SyncService:{0:yyyy-MM-dd HH:mm:sss}”,
DateTime.Now));

Thread.Sleep(5 * 60 * 1000);

_timer.Enabled = true;

}

public void Start()
{
_timer.Start();
_timer.Enabled = true;
}
public void Stop()
{
_timer.Stop();
_timer.Enabled = false;
}
}