- 创建一个Windows服务项目:解决方案(右击)——> 添加 ——> 新建项目——>项目类型选择Windows——>模板选择Windows服务 ,如图:
- 编写Windows服务程序
创建后会生成两个文件 Program.cs 和 Service1.cs(我已重命名为MyService.cs),编写服务内容:
具体服务代码:using System;
using System.Configuration;
using System.ServiceProcess;
using System.Threading; namespace WindowsServiceTest
{
public partial class MyService : ServiceBase
{ private Thread _thread = null;
private bool serviceIsRun = false; // 是否一直运行 public MyService()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
LogHelper.WriteLog("服务启动...");
serviceIsRun = true;
_thread = new Thread(CheckSrv);
_thread.Start();
} protected override void OnStop()
{
serviceIsRun = false;
LogHelper.WriteLog("服务停止...");
} protected void CheckSrv()
{
var beginTime = ConfigurationManager.AppSettings["BeginTime"];
var endTime = ConfigurationManager.AppSettings["EndTime"];
while (serviceIsRun)
{
try
{
if (IsRunTime(beginTime, endTime))
{
// TODO:
for (int i = ; i < ; i++)
{
if (!IsRunTime(beginTime, endTime))
{
Thread.Sleep( * );
}
else
{
LogHelper.WriteLog("当前数字:" + i);
}
}
}
else
{
Thread.Sleep( * );
LogHelper.WriteLog("未达到服务执行时间...");
}
}
catch (Exception ex)
{
LogHelper.WriteLog("服务发生异常:" + ex.ToString());
}
}
} /// <summary>
/// 判断程序是否在设置运行时间内
/// </summary>
/// <param name="startTime">开始执行时间</param>
/// <param name="overTime">执行结束时间</param>
/// <returns>true:在执行时间内,false:在执行时间外</returns>
private bool IsRunTime(string startTime, string overTime)
{
var flag = false; var beginTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime);
var endTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + overTime); if (beginTime <= endTime) // 当天
{
flag = beginTime <= DateTime.Now && DateTime.Now <= endTime;
}
else // 跨天
{
var zeroTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00");
flag = (beginTime <= DateTime.Now && DateTime.Now <= zeroTime.AddDays()) || (zeroTime <= DateTime.Now && DateTime.Now <= endTime);
} return flag;
}
}
}配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="LogPath" value="Log"/>
<add key="BeginTime" value="10:28"/>
<add key="EndTime" value="10:38"/>
</appSettings>
</configuration>日志代码:
using System;
using System.Configuration;
using System.IO;
using System.Text; namespace WindowsServiceTest
{
internal class LogHelper
{
/// <summary>
/// 记录日志
/// </summary>
/// <param name="logContext">日志内容</param>
public static void WriteLog(string logContext)
{
var logPath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["LogPath"].ToString();
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
var filePath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
var m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(, SeekOrigin.End);
var sb = new StringBuilder();
if (!string.IsNullOrEmpty(logContext))
{
sb.Append(Environment.NewLine);
sb.Append(logContext);
}
sb.Append(" "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")+Environment.NewLine);
m_streamWriter.WriteLine(sb.ToString());
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
}
}