您的位置:首页 > 其它

vs2015编写“windows服务”定时执行程序

2016-09-13 17:02 239 查看
参考文章:

http://www.cnblogs.com/xujie/p/5695673.html

上面的文章写的已经不错,有几点问题,进行了一下修改。

1.System.Timers.Timer控件从工具箱中拖入

在设计视图,工具箱,右键“选择项”,.NET Framework组件查找到System.Timers组件,然后勾选,确定。

再将刚才引入的Timer控件拖入调用。

2.Timer控件通过调用Start()和Stop()方法,而不是设置Enabled属性

在Service的OnStart方法里面调用Timer的Start方法;

在Service的OnStop方法里面调用Timer的Stop方法。

3.因为我们的Timer控件是拖入的,所以在设计页面双击即可编辑Elapsed时间的代码,不再需要进行绑定。

Service1.cs的完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Text;

namespace ReportClient
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
timer1.Interval = 1000; //1s
}

protected override void OnStart(string[] args)
{
timer1.Start();
this.WriteLog("【服务启动】");
}

protected override void OnStop()
{
timer1.Stop();
this.WriteLog("【服务停止】");
}

private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//时间控件定时任务
// 1. 访问接口
// 2. 记录日志
string res = this.GetReport("id=555&name=vs", "http://localhost:8090/test.php");
this.WriteLog(res);
}

private string GetReport(string RequestPara, string Url)
{
RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara);
WebRequest hr = HttpWebRequest.Create(Url + RequestPara);
byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara);
hr.Method = "GET";
try
{
System.Net.WebResponse response = hr.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
string ReturnVal = reader.ReadToEnd();
reader.Close();
response.Close();
return ReturnVal;
}
catch (System.Net.WebException wex)
{
string error_info = "WebException=" + wex.ToString() + ",wex.Status=" + wex.Status;
return error_info;
}
}
private void WriteLog(string msg)
{
//该日志文件会存在windows服务程序目录下
string path = AppDomain.CurrentDomain.BaseDirectory + @"\log\";
path += DateTime.Now.Year + "_" + DateTime.Now.Month + "_access_log.txt";
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
FileStream fs;
fs = File.Create(path);
fs.Close();
}

using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now.ToString() + "   " + msg);
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: