I am writing an Notification service, for that i need to send reminders based on a time period. This is how I did. Here i am Configuring notification time and service interval time in app.config. For me, notification time is the time when to execute the logic and service interval time will tell the timer when to stop and start. If we want we can make this data driven as well. I have added a timer control. Here is the sample code snippet here for this.
public partial class Service1 : ServiceBase{private System.Timers.Timer timer = null;private NotificationClass nc = new NotificationClass();private string notificationTime = ConfigurationManager.AppSettings["notificationTime"];// Default time to start and stop the timer.private string serviceInterval = ConfigurationManager.AppSettings["serviceInterval"];public Service1(){InitializeComponent();timer = new System.Timers.Timer(Convert.ToDouble(serviceInterval));timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);}private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e){// Compare this notification time with your time...if (DateTime.Now.ToShortTimeString() == notificationTime){this.timer.Enabled = false;this.timer.AutoReset = false;// Do the logicnc.BirthdayReminder();this.timer.Start();}}protected override void OnStart(string[] args){// TODO: Add code here to start your service.timer.AutoReset = true;timer.Enabled = true;timer.Start();}protected override void OnStop(){// TODO: Add code here to perform any tear-down necessary to stop your service.timer.AutoReset = false;timer.Enabled = false;}}
No comments:
Post a Comment