public partial class TimerByThread : ServiceBase
{
public TimerByThread()
{
InitializeComponent();
}
Thread thread = new Thread(new ThreadStart(WriteLog.WriteLogToD));
protected override void OnStart(string[] args)
{
try
{
WriteLog.WriteLogToD("开始服务");
thread.Start();
}
catch (Exception e)
{
WriteLog.WriteLogToD("开始时出错:" + e.Message);
}
}
protected override void OnStop()
{
try
{
WriteLog.WriteLogToD("停止服务");
thread.Abort();
}
catch (Exception e)
{
WriteLog.WriteLogToD("停止时出错:"+e.Message);
}
}
}
///////////=================WriteLog.WriteLogToD
public class WriteLog
{
public static void WriteLogToD()
{
while (true)
{
try
{
FileStream fs = new FileStream("D:\B.txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
sw.WriteLine("定时线程执行:"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.Close();
fs.Close();
Thread.Sleep(1000 * 60);
}
catch (Exception e)
{
WriteLog.WriteLogToD("定时线程出错:" + e.Message);
}
}
}
public static void WriteLogToD(string text)
{
FileStream fs = new FileStream("D:\B.txt", FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:" + text));
sw.Close();
fs.Close();
}
}