这里我目前在SQL Server 2008数据库中有一些日期值。我想在该日期值等于当前日期时向特定邮件地址发送电子邮件警报。想象一下自动化的b日祝福软件。
以下是我用于电子邮件功能的代码。它没有任何问题。
private void sendMailMessage()
{
try
{
MailMessage myMessage = new MailMessage();
myMessage.From = new MailAddress("noreply@somewhere.com", "Online Alert System");
myMessage.To.Add(new MailAddress("someone@somewhere.com"));
myMessage.Subject = "Test Mail";
myMessage.Body = "This is test mail from OAS.";
myMessage.IsBodyHtml = true;
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Host="smtp.gmail.com";
mySmtpClient.Port= 587;
mySmtpClient.Credentials = new NetworkCredential("noreply@somewhere.com", "password");
mySmtpClient.EnableSsl = true;
mySmtpClient.Send(myMessage);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
但我想使用widows服务来做到这一点。请解释我怎么能这样做。在这种情况下,我对Windows服务知之甚少。
提前致谢..!
答案 0 :(得分:0)
// try the following code
//in app.config add the following key
// <add key="starttime" value="00.00"/>
public static System.Timers.Timer Timer;
Double _timeinterval;
public static bool IstimerEnabled = false;
protected override void OnStart(string[] args)
{
try
{
Timer = new System.Timers.Timer();
string starttime = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["starttime"]);
double mins = Convert.ToDouble(starttime);
DateTime t = DateTime.Now.Date.AddHours(mins);
TimeSpan ts = new TimeSpan();
ts = t.AddDays(1) - System.DateTime.Now;
log.WriteEntry("BBPush Service timespan ts--" + ts.ToString());
if (ts.TotalMilliseconds < 0)
{
ts = t.AddDays(1) - System.DateTime.Now;
}
_timeinterval = ts.TotalMilliseconds;
Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
Timer.Interval = _timeinterval;
Timer.Enabled = true;
}
catch (Exception ex)
{
log.WriteEntry("exception :" + ex.ToString());
}
finally
{
IstimerEnabled = false;
Timer.Start();
}
}
protected override void OnStop()
{
Timer.Stop();
Timer.Dispose();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// write your code here or call the method that checks the current date with dob in your table ,fetch the matching emailid and call the mail sending method.
//after this method timer is set for 24 hrs.
Timer.Interval = 86400000;
}