我最近从vb.net转移到C#和我有开创我已创建的Windows服务的问题。我希望该服务在我的app.config文件中每天读取一次。在vb.net我用了一个定时器,并呼吁方法:在设定时间启动Windows服务
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
我需要我的代码来调用OnTimedEvent每30秒检查时间从配置文件,然后运行我的代码。任何帮助赞赏
你在哪里启动计时器?我在任何地方都看不到。 – Oded
我在服务代码的OnStart中这样做:protected override void OnStart(string [] args) { base.OnStart(args); // TODO:将您的起始代码放在这里 alarm.Enabled = true; alarm.Start(); } // end onStart –
我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –