csharp 一个控制台应用程序,以设定的间隔执行代码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 一个控制台应用程序,以设定的间隔执行代码相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OrangeMSE.Data;
using OrangeMSE.Connector;
using System.Threading;
using log4net;
using log4net.Config;
using System.Configuration;
using System.Reflection;
namespace X
{
class Program
{
public Timer timer = null;
public static Random rnd = new Random();
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
XmlConfigurator.Configure();
log.Info("point collector started");
timer = new Timer(TimerCallback, null, 0, 200000000);
bool exit = false;
while (!exit)
{
exit = (Console.ReadLine() == "exit");
}
}
private static void TimerCallback(Object o)
{
log.Info("collector started");
try
{
//Code here
}
catch(Exception ex)
{
HandleException(ex);
}
finally
{
log.Info("collector ended");
}
}
public static void HandleException(Exception ex)
{
log.Error("exception = " + ex.ToString());
if (bool.Parse(ConfigurationManager.AppSettings["EnableEmail"].ToString()))
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
ConfigurationManager.AppSettings["Email"].ToString().Split(';').ToList().ForEach(x =>
{
message.To.Add(x);
});
message.Subject = "Error";
message.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["From"].ToString());
message.Body = ex.ToString();
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["Smtp"].ToString());
smtp.Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"].ToString());
smtp.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["SmtpSSL"].ToString());
smtp.Credentials = new System.Net.NetworkCredential(
ConfigurationManager.AppSettings["SmtpUser"].ToString(),
ConfigurationManager.AppSettings["SmtpPass"].ToString()
);
smtp.Send(message);
}
}
}
}
以上是关于csharp 一个控制台应用程序,以设定的间隔执行代码的主要内容,如果未能解决你的问题,请参考以下文章