首先添加一个.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;
}
}