我最近從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/)」,其中的共識是「不,他們不應該」。 –