C#制作Windows service服务系列二:演示一个定期执行的windows服务(windows service)
2010-09-30 21:04:34 来源:WEB开发网经常有人问起如何让程序定期自动执行,除了像系统任务和SQL JOB/DTS等都可以满足不同的用户需求外,这里演示了如何做一个简单的windows serivce的框架。主要的功能是按照预先设定的时间间隔来执行类似的操作,比如抓取网页,抓取天气预报,群发邮件等。
假定用户有如下代码需要定期自动执行:
1 获取内容#region 获取内容
2 /**//// <summary>
3 /// 获取内容,by tony 2009.9,16
4 /// 邀月(downmoon):3w@live.cn
5 /// </summary>
6 public void GetContentByMethods(bool isDelteOldFile)
7 {
8 System.Text.StringBuilder builder = new System.Text.StringBuilder();
9
10 try
11 {
12 DeleteOldFile#region DeleteOldFile
13 if (isDelteOldFile)
14 {
15 string path = Globals.BakPath;
16 if (System.IO.Directory.Exists(path))
17 {
18 string[] strFiles = System.IO.Directory.GetFiles(path);
19 foreach (string strFile in strFiles)
20 {
21 System.IO.File.Delete(strFile);
22 }
23 }
24 }
25 #endregion
26 My Methods#region My Methods
27 int tempCount = 0;
28 string temp = "Operation_{0} was sucessfully executed at {1} by Operator_{2}!";
29 string temp2 = string.Empty;
30 string filename = Globals.CreateXMLDir(Globals.BakPath) + Globals.StrTempDate + ".txt";
31 for (int k = 0; k < Globals.TopCount; k++)
32 {
33 temp2 = string.Empty;
34 //此处从数据表中读取数据,做一些事情,比如发邮件,抓取网页内容等。
35 temp2 = string.Format(temp, k, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), k) + "\r\n";
36 builder.Append(temp2);
37 tempCount++;
38 }
39 builder.Append("total [" + tempCount + "] records was executed this time!");
40 SaveFileResult(filename, builder.ToString());
41 #endregion
42 }
43 catch (Exception ex) { string s = ex.Message; }
44 }