首先打开VS,创建一个Windows Service 程序
进入后先点击右键进入代码,编写一个简单的例子(往C盘下写一个名为aa的文本文档,内容为系统时间):
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
Thread th = null;
public Service1()
{
InitializeComponent();
th = new Thread (new ThreadStart(MyMethod));
}
void MyMethod()
{
while(true)
{
StreamWriter sw = new StreamWriter(@"c:\aa.txt",true);
sw.WriteLine(DateTime.Now.ToString());
sw.Flush();
sw.Close();
Thread.Sleep(5*1000);
}
}
}
protected override void OnStart(string[] args)
{
th.Start();
while(true)
{
if(System.DateTime.Now.ToShortTimeString() == "14:20")
{
if(th.ThreadState = System.Threading.ThreadState.Suspended)
{
th.Resume();
Thread.Sleep(10*1000);
}
else
{
th.Suspend();
Thread.Sleep(30*1000);
}
}
}
}
protected override void OnStop()
{
if(th.IsAlive)
{
th.Abort();
}
}
protected override void OnPause()
{
base.OnPause();
}
}
写完代码后,返回设计界面,注意一定要先再属性里先把自己想改的名字写入,这样再右键添加安装程序
把ServiceInstaller1的Modifiers改为private
把ServiceProcessInstaller1的Account 改为 localsystem
然后再注册表里注册下就搞定了