1.VS-》文件-》新建项目,弹出窗口中选择Visual C#-》windows-》windows服务
2.在新建的工程中,点击Service1.cs文件,切换到代码视图:
3.生成工程,在bin目录下会生成exe文件
4.向系统添加该服务:
(1).找到系统盘下的.net路径:本机是C:\Windows\Microsoft.NET\Framework\v4.0.30319,找到其中的InstallUtil.exe
(2).找到工程文件路径下的bin\Debug\项目名称.exe
(3).打开命令行工具,输入:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe空格D:\WebSites\TimedTask\bin\Debug\项目名称.exe
执行成功后,会在Windows的服务中,出现了刚刚添加的服务的名称。
注意:中文字符空格是表示敲击空格键。
5.启动该服务即可。
6.调试:
服务已启动时,在VS中选择调试-》附加到进程,可找到该服务名称,附加即可调试。
2.在新建的工程中,点击Service1.cs文件,切换到代码视图:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Timers;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Net.Mail;
namespace TimedTask
{
public partial class Service1 : ServiceBase
{
Timer timer;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer = new Timer(60000);//1000=1s,此处为1分钟
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer.Dispose();
}
//定时执行的任务
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
string time = DateTime.Now.AddDays(1).ToShortDateString() + " " + DateTime.Now.ToLongTimeString().ToString();
string filePath = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
StreamWriter sw = null;
if (!File.Exists(filePath))
{
sw = File.CreateText(filePath);
}
else
{
sw = File.AppendText(filePath);
}
sw.Write("访问时间:" + time + Environment.NewLine);
sw.Close();
}
}
}
3.生成工程,在bin目录下会生成exe文件
4.向系统添加该服务:
(1).找到系统盘下的.net路径:本机是C:\Windows\Microsoft.NET\Framework\v4.0.30319,找到其中的InstallUtil.exe
(2).找到工程文件路径下的bin\Debug\项目名称.exe
(3).打开命令行工具,输入:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe空格D:\WebSites\TimedTask\bin\Debug\项目名称.exe
执行成功后,会在Windows的服务中,出现了刚刚添加的服务的名称。
注意:中文字符空格是表示敲击空格键。
5.启动该服务即可。
6.调试:
服务已启动时,在VS中选择调试-》附加到进程,可找到该服务名称,附加即可调试。