定时任务之windows服务

定时任务,比如在什么时间点,去执行什么操作。
原来的定时任务都是在什么时间点,在电脑上打开“任务计划程序”,部署就行了。但是,有一个定时任务,时间不知道,是由客户设置的,可以修改的时间,就木有办法使用任务计划进行定时任务的部署了。

然后就使用到了windows服务。这个就是你写一个服务,然后在电脑上安装,服务一直运行,直到与时间相匹配时,去执行设置的操作;

使用的是VS2012:

新建项目:

新建完的项目:

右侧的Service1.cs就是代码执行的主要地方,可以进行名称的修改:

右侧Service1.cs下的Service1就是代码重灾区,双击会出现在左侧,红色区域内就是你要执行操作的操作;

主要代码区域的代码,多个时间的任务,服务是每秒钟执行一次,当遇到对的时间,就会去执行对应的任务:

  1 Timer timer = new Timer();
  2         protected override void OnStart(string[] args)
  3         {
  4             timer.Interval = 1000; // 一秒执行一次
  5             timer.AutoReset = true;   //执行一次 false,一直执行true   
  6             timer.Enabled = true;
  7             timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
  8             timer.Start();
  9         }
 10 
 11         protected override void OnStop()
 12         {
 13             timer.Stop();
 18         }
 19 
 20         private void timer_Elapsed(object sender, ElapsedEventArgs e)
 21         {
 22             using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"E:log.txt", true))
 23             {
 24                 //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Service Start.");
 25 
 26                 var str = ConfigurationManager.AppSettings["IsOpen"];
 27                 if (str != "true")//不执行
 28                 {
 29                     return;
 30                 }
 31                 var compId = ConfigurationManager.AppSettings["CompId"];
 32                 //判断是否开启短信功能
 33                 string sql = "select * from ClockIn_MessageWarningTime where CompId = '" + compId + "'";
 34                 DataSet ds = DbHelperSQL.Query(sql);
 35                 if (ds == null || ds.Tables.Count <= 0 || ds.Tables[0].Rows.Count <= 0)
 36                 {
 37                     return;
 38                 }
 39                 DataRow dr = ds.Tables[0].Rows[0];
 40                 if (dr["IsOpen"].ToString() != "1")//=1开启
 41                 { return; }
 42 
 43 
 44                 SendMessageJudge(compId, dr,sw);
 45             }
 46  
 47         }
 48 
 49         public int nowhour;
 50         public int nowminutes;
 51         public int nowsecond;
 52 
 53         /// <summary>
 54         /// 短信发送判断
 55         /// </summary>
 56         /// <param name="compId">厂区id</param>
 57         /// <param name="dr">预警时间</param>
 58         private void SendMessageJudge(string compId, DataRow dr, System.IO.StreamWriter sw)
 59         {
 60             List<string> ClockInType = new List<string>();
 61             string ChangCurrentTime = "", ChangHomeTime = "";
 62             //时分秒----当班c和到家h
 63             int cch = -1, ccm = -1, ccs = -1;
 64             int chh = -1, chm = -1, chs = -1;
 65             string FirstCurrentTime = "", FirstHomeTime = "";
 66             int fch = -1, fcm = -1, fcs = -1;
 67             int fhh = -1, fhm = -1, fhs = -1;
 68             string SecondCurrentTime = "", SecondHomeTime = "";
 69             int sch = -1, scm = -1, scs = -1;
 70             int shh = -1, shm = -1, shs = -1;
 71             string ThirdCurrentTime = "", ThirdHomeTime = "";
 72             int tch = -1, tcm = -1, tcs = -1;
 73             int thh = -1, thm = -1, ths = -1;
 74 
 75             if (dr["ChangCurrentTime"] != null || dr["ChangCurrentTime"].ToString() != "")
 76             {
 77                 ChangCurrentTime = dr["ChangCurrentTime"].ToString();
 78                 cch = TimeSpan.Parse(ChangCurrentTime).Hours;
 79                 ccm = TimeSpan.Parse(ChangCurrentTime).Minutes;
 80                 ccs = TimeSpan.Parse(ChangCurrentTime).Seconds;
 81             }
 82             if (dr["ChangHomeTime"] != null || dr["ChangHomeTime"].ToString() != "")
 83             {
 84                 ChangHomeTime = dr["ChangHomeTime"].ToString();
 85                 chh = TimeSpan.Parse(ChangHomeTime).Hours;
 86                 chm = TimeSpan.Parse(ChangHomeTime).Minutes;
 87                 chs = TimeSpan.Parse(ChangHomeTime).Seconds;
 88             }
 89             if (dr["FirstCurrentTime"] != null || dr["FirstCurrentTime"].ToString() != "")
 90             {
 91                 FirstCurrentTime = dr["FirstCurrentTime"].ToString();
 92                 fch = TimeSpan.Parse(FirstCurrentTime).Hours;
 93                 fcm = TimeSpan.Parse(FirstCurrentTime).Minutes;
 94                 fcs = TimeSpan.Parse(FirstCurrentTime).Seconds;
 95             }
 96             if (dr["FirstHomeTime"] != null || dr["FirstHomeTime"].ToString() != "")
 97             {
 98                 FirstHomeTime = dr["FirstHomeTime"].ToString();
 99                 fhh = TimeSpan.Parse(FirstHomeTime).Hours;
100                 fhm = TimeSpan.Parse(FirstHomeTime).Minutes;
101                 fhs = TimeSpan.Parse(FirstHomeTime).Seconds;
102             }
132             //现在时间 小时        
133             nowhour = Convert.ToInt32(DateTime.Now.Hour.ToString());//10       
134             //现在分钟        
135             nowminutes = Convert.ToInt32(DateTime.Now.Minute.ToString());//5
136             //现在秒针
137             nowsecond = Convert.ToInt32(DateTime.Now.Second.ToString());//5
138 
139             if (nowhour == cch && nowminutes == ccm && nowsecond == ccs)//常白当班
140             {143                 DepartmentBeginSendMessage(compId, "当班", sw);
144             }
145             if (nowhour == chh && nowminutes == chm && nowsecond == chs)//常白到家
146             {149                 DepartmentBeginSendMessage(compId, "到家", sw);
150             }
151             if (nowhour == fch && nowminutes == fcm && nowsecond == fcs)//第一班当班
152             {155                 TeamBeginSendMessage(compId, "当班", sw);
156             }
157             if (nowhour == fhh && nowminutes == fhm && nowsecond == fhs)//第一班到家
158             {161                 TeamBeginSendMessage(compId, "到家", sw);
162             }
188 if (ClockInType.Count <= 0) 189 { 190 //Logger.loggerInfo("结束,未找到打卡类型。"); 191 return; 192 } 193 194 }

功能代码完事之后

回到这个界面,就是Servcie.cs,

然后在上面右单击,选择 “添加安装程序”,就会多出了这个文件:

右单击serviceProcessInstaller1,属性,Account选择LocalSystem;
右单击serviceInstaller1,属性,StartType选择Automatic,Description填写这个服务的信息,写清楚,以免被误删,DisplayName和ServiceName可以写成一致的,命一个名字即可(比如叫FW);

然后就是按F6重新生成项目,在bin-->debug中,就是需要部署服务的文件了;

这些只是完成了一半;剩下的就是部署服务的问题了。

在下面的电脑路径中,找到    InstallUtil.exe  ,复制出来,放在debug目录中;

C:WindowsMicrosoft.NETFramework64v4.0.30319

可以把debug中的文件都拷贝出来操作一下内容:

下面的操作就是网上大部分是写一个bat文件,然后去部署服务,可能是我太笨了,不知道哪里有问题,总是不成功。所以我就没有用那种方式。

在你的debug文件中,把你写的XXXX.exe和复制进来的 InstallUtil.exe  都获取到管理员权限;

然后,点击你的XXXX.exe,不要松开,拖动到  InstallUtil.exe  上;

打开电脑的服务,去看看有没有你部署的XXXX.exe。应该会有的。
当你不想要这个服务的时候,想卸载掉,就打开cmd,输入口令:sc delete FW(服务的名称,上面命名的时候写的名字)

写 的很乱。。。。。很是尴尬。。。。

可以参考别人写的:https://blog.csdn.net/shujudeliu/article/details/81237141

原文地址:https://www.cnblogs.com/syp1Blog/p/windows_Service.html