第一添加一个.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(IService(Service)Collection
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;
}
}

相关文章

网站地图xml地图