【.Net 学习系列】-- .Net 指定时间段内定时执行…

2018-06-18 04:38:08来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

  1. 创建一个Windows服务项目:解决方案(右击)——> 添加 ——> 新建项目——>项目类型选择Windows——>模板选择Windows服务 ,如图:
  2. 编写Windows服务程序
    创建后会生成两个文件 Program.cs 和 Service1.cs(我已重命名为MyService.cs),编写服务内容:

    具体服务代码:
     1 using System;
     2 using System.Configuration;
     3 using System.ServiceProcess;
     4 using System.Threading;
     5 
     6 namespace WindowsServiceTest
     7 {
     8     public partial class MyService : ServiceBase
     9     {
    10 
    11         private Thread _thread = null;
    12         private bool serviceIsRun = false;  // 是否一直运行
    13 
    14         public MyService()
    15         {
    16             InitializeComponent();
    17         }
    18 
    19         protected override void OnStart(string[] args)
    20         {
    21             LogHelper.WriteLog("服务启动...");
    22             serviceIsRun = true;
    23             _thread = new Thread(CheckSrv);
    24             _thread.Start();
    25         }
    26 
    27         protected override void OnStop()
    28         {
    29             serviceIsRun = false;
    30             LogHelper.WriteLog("服务停止...");
    31         }
    32 
    33         protected void CheckSrv()
    34         {
    35             var beginTime = ConfigurationManager.AppSettings["BeginTime"];
    36             var endTime = ConfigurationManager.AppSettings["EndTime"];
    37             while (serviceIsRun)
    38             {
    39                 try
    40                 {
    41                     if (IsRunTime(beginTime, endTime))
    42                     {
    43                         // TODO:
    44                         for (int i = 0; i < 10; i++)
    45                         {
    46                             if (!IsRunTime(beginTime, endTime))
    47                             {
    48                                 Thread.Sleep(1000 * 2);
    49                             }
    50                             else
    51                             {
    52                                 LogHelper.WriteLog("当前数字:" + i);
    53                             }
    54                         }
    55                     }
    56                     else
    57                     {
    58                         Thread.Sleep(1000 * 5);
    59                         LogHelper.WriteLog("未达到服务执行时间...");
    60                     }
    61                 }
    62                 catch (Exception ex)
    63                 {
    64                     LogHelper.WriteLog("服务发生异常:" + ex.ToString());
    65                 }
    66             }
    67         }
    68 
    69         /// <summary>
    70         /// 判断程序是否在设置运行时间内
    71         /// </summary>
    72         /// <param name="startTime">开始执行时间</param>
    73         /// <param name="overTime">执行结束时间</param>
    74         /// <returns>true:在执行时间内,false:在执行时间外</returns>
    75         private bool IsRunTime(string startTime, string overTime)
    76         {
    77             var flag = false;
    78 
    79             var beginTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + startTime);
    80             var endTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " " + overTime);
    81 
    82             if (beginTime <= endTime)   // 当天
    83             {
    84                 flag = beginTime <= DateTime.Now && DateTime.Now <= endTime;
    85             }
    86             else    // 跨天
    87             {
    88                 var zeroTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00");
    89                 flag = (beginTime <= DateTime.Now && DateTime.Now <= zeroTime.AddDays(1)) || (zeroTime <= DateTime.Now && DateTime.Now <= endTime);
    90             }
    91 
    92             return flag;
    93         }
    94     }
    95 }
    View Code

    配置文件:

    1 <?xml version="1.0" encoding="utf-8" ?>
    2 <configuration>
    3   <appSettings>
    4     <add key="LogPath" value="Log"/>
    5     <add key="BeginTime" value="10:28"/>
    6     <add key="EndTime" value="10:38"/>
    7   </appSettings>
    8 </configuration>
    View Code

    日志代码:

     1 using System;
     2 using System.Configuration;
     3 using System.IO;
     4 using System.Text;
     5 
     6 namespace WindowsServiceTest
     7 {
     8     internal class LogHelper
     9     {
    10         /// <summary>
    11         /// 记录日志
    12         /// </summary>
    13         /// <param name="logContext">日志内容</param>
    14         public static void WriteLog(string logContext)
    15         {
    16             var logPath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["LogPath"].ToString();
    17             if (!Directory.Exists(logPath))
    18             {
    19                 Directory.CreateDirectory(logPath);
    20             }
    21             var filePath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    22             var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
    23             var m_streamWriter = new StreamWriter(fs);
    24             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    25             var sb = new StringBuilder();
    26             if (!string.IsNullOrEmpty(logContext))
    27             {
    28                 sb.Append(Environment.NewLine);
    29                 sb.Append(logContext);
    30             }
    31             sb.Append(" "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")+Environment.NewLine);
    32             m_streamWriter.WriteLine(sb.ToString());
    33             m_streamWriter.Flush();
    34             m_streamWriter.Close();
    35             fs.Close();
    36         }
    37     }
    38 }
    View Code

     

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:4.Windows Server2012 R2里面部署 MVC 的网站

下一篇:微信开发:如何一键拨打电话