1 新建 windows 服务 项目
2 添加自定义设置文件
3 配置基本参数,
在程序中可以如下使用 这里定义的常量 Timing_WX_L.Settings1.Default.span,
4 设置安装参数 可参考 http://jingyan.baidu.com/article/fa4125acb71a8628ac709226.html
-
一、打开Service1.cs视图界面
-
在视图内右键-->添加安装程序
-
二、项目中添加了ProjectInstaller.cs文件,该文件中视图自动会添加俩个组件
serviceProcessInstaller1
serviceInstaller1
-
四、在视图内右键-->添加安装程序
-
五、项目中添加了ProjectInstaller.cs文件,该文件中视图自动会添加俩个组件
serviceProcessInstaller1
serviceInstaller1
-
六、选中serviceProcessInstaller1组件,查看属性,设置account为LocalSystem
-
七、选中serviceInstaller1组件,查看属性
设置ServiceName的值, 该值表示在系统服务中的名称
设置StartType, 如果为Manual则手动启动,默认停止,如果为Automatic为自动启动
设置Description,添加服务描述
-
八、重新生成项目
---------------------------------------------------------------以上是准备工作----------------------------------------------------------------------
5 在程序运行主程序里,填写如下程序
partial class Wx_pay_L : ServiceBase
{
Timer _timer = new Timer();
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "logWX.txt";// "D:\\ws.txt";
static int i = 0;
static int span = 0;
public Wx_pay_L()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//时间间隔
span = Convert.ToInt32(Timing_WX_L.Settings1.Default.span);
_timer.AutoReset = true;
_timer.Interval = 1000 * span;// 默认*1000是1秒
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
try
{
TextWriter sw = new StreamWriter(filePath, true);
sw.WriteLine("------" + System.DateTime.Now.ToString());
sw.WriteLine("服务启动。");
sw.Flush();
sw.Close();
}
catch
{ }
_timer.Start();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
try
{
string uri = "http://localhost:802/api/pay/everyGetAllData";
WebClient wc = new WebClient();
string r = wc.DownloadString(uri);
}
catch (Exception ex)
{
try
{
TextWriter sw = new StreamWriter(filePath, true);
sw.WriteLine("------" + System.DateTime.Now.ToString());
sw.WriteLine(ex.Message);
sw.Flush();
sw.Close();
}
catch
{ }
}
}
protected override void OnStop()
{
try
{
TextWriter sw = new StreamWriter(filePath, true);
sw.WriteLine("------" + System.DateTime.Now.ToString());
sw.WriteLine("服务停止。");
sw.Flush();
sw.Close();
}
catch
{ }
}
//private static string GetAppConfig(string strKey) 这里是直接引用 webconfig
//{
// foreach (string key in ConfigurationManager.AppSettings)
// {
// if (key == strKey)
// {
// return ConfigurationManager.AppSettings[strKey];
// }
// }
// return null;
//}
}
6 生成之后的bin目录里就有exe文件,之后运行如下步骤安装和卸载其为系统服务
一、 点击 开始,运行中输入cmd,获取命令提示符
win7需要已管理员的身份启动,否则无法安装
二、输入 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 回车
切换当前目录,此处需要注意的是,在C:\Windows\Microsoft.NET\Framework目录下有很多类似版本,具体去哪个目录要看项目的运行环境,例 如果是.net framework2.0则需要输入 cd C:\Windows\Microsoft.NET\Framework\v2.0.50727
三、输入 InstallUtil.exe E:\TestApp\Winform\WinServiceTest\WinServiceTest\bin\Debug\WinServiceTest.exe 回车
说明:E:\TestApp\Winform\WinServiceTest\WinServiceTest\bin\Debug\WinServiceTest.exe表示项目生成的exe文件位置
四、打开服务,就可以看到已经安装的服务了;
卸载很简单,打开cmd, 直接输入 sc delete WinServiceTest便可。还有问题可以参考文件下面的参考网址