windows 服务问题 启动后自动停止
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
namespace WindowsServiceTime
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
tim = new Timer();
tim.Interval = 1000;
tim.Elapsed += new ElapsedEventHandler(tim_Elapsed);
}
bool state1 = true;
bool state2 = true;
void tim_Elapsed(object sender, ElapsedEventArgs e)
{
int hour = DateTime.Now.Hour;
if ((hour>= 0) && (hour < 12) &&this.state1)
{
this.print(DateTime.Now.ToString()+":上午好!");
this.state1 = false;
this.state2 = true;
}
else if ((hour>= 12) && (hour < 18) && this.state2)
{
this.print(DateTime.Now.ToString()+":下午好!");
this.state2 = false;
this.state1 = true;
}
}
private Timer tim ;
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
this.print(DateTime.Now.ToString() + ":服务启动!");
this.tim.Start();
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
this.print(DateTime.Now.ToString() + ":服务关闭!");
this.tim.Stop();
}
private void print(string info)
{
StreamWriter sw = new StreamWriter("F:\\c#\\WindowsServiceTime\\log.txt",true,Encoding.Default);
sw.WriteLine(info);
sw.Flush();
sw.Close();
}
}
}
--------------------编程问答--------------------
补充:.NET技术 , C#