我最近从 vb.net 迁移到 C#,但在启动我创建的 Windows 服务时遇到问题。我希望每天从我的 app.config 文件中读取该服务。在 vb.net 中,我使用了一个 Timer 并调用了一个方法:
Private WithEvents Alarm As Timer = New Timer(30000)
Public Sub OnTimedEvent(ByVal source As Object, ByVal e As ElapsedEventArgs) Handles Alarm.Elapsed
这是我到目前为止的 C# 代码:
namespace MyWindowsService
{
class Program : ServiceBase
{
Timer alarm = new Timer(30000);
public string str_dbserver;
public string str_year;
public string str_time;
public string str_dbConnection;
bool service_running;
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "MyWindowsService";
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
service_running = false;
//declare variables and get info from config file
DateTime dtNow;
dtNow = DateTime.Now;
System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
str_dbserver = Convert.ToString(configurationAppSettings.GetValue("dbServer", typeof(System.String)));
str_year = Convert.ToString(configurationAppSettings.GetValue("sYear", typeof(System.String)));
str_time = Convert.ToString(configurationAppSettings.GetValue("stime", typeof(System.String)));
//split time from config to get hour, minute, second
string[] str_atime = str_time.Split(new string[] { ":" }, StringSplitOptions.None);
//check that service is not currently running and time matches config file
if (DateTime.Now.Hour == Convert.ToInt32(str_atime[0]) && DateTime.Now.Minute == Convert.ToInt32(str_atime[1]) && service_running == false)
{
//service now running so write to log and send email notification
service_running = true;
try
{
//call functions containing service code here
Function1();
Function2();
}
catch (Exception ex)
{
} //end try/catch
//service now finished, sleep for 60 seconds
service_running = false;
} //end if
} //end OnTimedEvent
我需要我的代码每 30 秒调用一次 OnTimedEvent 以检查配置文件中的时间,然后运行我的代码。任何帮助表示赞赏