windows服务加定时器实现

首先在项目中添加windows服务

然后双击“MainService.cs”,在上面点右键“打开代码”

以下是我的实例代码

  partial class MainService : ServiceBase
    {
        int iHour = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["HH"]);//开始时间小时
     int iMinute = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["MM"]);//开始分钟
     int iSecond = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["SS"]);//开始秒钟         public MainService()         {            InitializeComponent();         }      /// <summary>
     /// 服务开启
     /// </summary>
        protected override void OnStart(string[] args)         {
       System.Timers.Timer timer1 = neew System.Timers.Timer();
       timer1.Inteval = 1000;//1000毫秒即1秒
       timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);//达到任务时间时的执行事件
       timer1.AutoReset = true;//true为一直执行
       timer1.Enabled = true;             WriteLog("MainService服务启动-------------->",true);         }

     private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
     {
       int inHour = e.SignalTime.Hour;
       int inMinute = e.SignalTime.Minute;
       int inSecond = e.SignalTime.Second;
       if(inHour == iHour && inMinute == iMinute && inSecond == iSecond)
       {//定时器时间到达我们规定的时间
          WriteLog("定时任务执行开始",true);
          try
          {
             //执行内容,你需要执行的代码
          }
          catch(Exception ex)
          {
            WriteLog("定时任务执行失败!",true);
            WriteLog("失败原因:" + ex.Message,false);
          }
          WriteLog("定时任务执行结束!",true);
       }
     }
     /// <summary>
     /// 服务关闭
     /// </summary>
        protected override void OnStop()         
     {          
       WriteLog("MainService服务关闭----------->",true);  
     }

     /// <summary>
     /// 日志输出
     /// </summary>
     prevate void WriteLog(string content,bool isAddTime)
     {
       string txtPath = System.Configuration.ConfigurationSettings.AppSettings["LogPath"].ToString();//日志路径
     string txtFile = DateTime.Now.ToString("yyyyMMdd") + ".txt";
       if(!Directory.Exists(txtPath))
        Directory.CreateDirectory(txtPath);
       if(isAddTime)
       File.AppendAllText(txtPath + txtFile,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + content + "\r\n"); 
       else
         File.AppendAllText(txtPath + txtFile,content + "\r\n");
     }
  }

项目中添加了ProjectInstaller.cs文件,该文件中视图自动会添加俩个组件

serviceProcessInstaller1

serviceInstaller1

可以看见项目中多了如下文件和组件,serviceProcessInstaller1、serviceInstaller1是自动生成的

设置组件serviceInstaller1的主要属性,ServiceName: 服务系统标识,在cmd命令中执行sr start/stop/query等等命令时候使用,用来唯一标识一个Window服务,这个千万要注意,别弄混了!

设置ServiceName的值, 该值表示在系统服务中的名称

设置StartType, 如果为Manual则手动启动,默认停止,如果为Automatic为自动启动

设置Description,添加服务描述

 

设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;

然后重新生成项目,生成成功!

/********************************************************************************************以下为安装*****************************************************************************************/

首先以管理员身份运行cmd(必须,否则会不成功),注,以下的v4.0.30319对应你项目使用的framework版本,若用的2.0版本则替换为v.2.0.50727

  输入: cd C:\Windows\Microsoft.NET\Framework\v4.0.30319  InstallUtil.exe  你的生成的windows服务exe路径(bin/debug中)

卸载   输入 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319 InstallUtil.exe -u 你的生成的windows服务exe路径(bin/debug中)

/*************************************************************************************************************************************************************************************************/

因嫌以上的安装卸载太麻烦,我将安装卸载卸载了bat批处理文件中,如下

在windows服务类库中添加install.txt文件和uninstall.txt改名为install.bat和uninstall.bat,注意编码格式不要用utf-8,使用ANSI

在install.bat文件中写入以下代码

@echo off

set filename = "%~dp0你的windows服务名称.exe"

set servicename = 定义的服务名称

set Frameworkdc = %SystemRoot%\Microsoft.NET\Framework\v4.0.30319

if exist "%Frameworkdc%" goto netOld

:DispError

echo 您的机器上没有安装 .net Framework 4.0,安装即将终止

echo 您的机器上没有安装 .net Framework 4.0,安装即将终止 > InstallService.log

goto LastEnd

:netOld

cd %Frameworkdc%

echo 您的机器上安装了相应的.net Framework 4.0,可以安装本服务.

echo 您的机器上安装了相应的.net Framework 4.0,可以安装本服务 > InstallService.log

echo.

echo. >> InstallService.log

echo **************************

echo 安装服务 %filename%

%Frameworkdc%\InstallUtil.exe  %filename% >> InstallService.log

echo 启动服务

net start %servicename% >> InstallService.log

echo **************************

echo 操作结束,可以查看日志文件InstallService.log中具体的操作结果。

:LastEnd

pause

rem exit

在uninstall.bat中写入以下代码

@echo off

set filename = "%~dp0生成ext名称.exe"

set servicename = 自定义的服务名称

 set Frameworkdc = %SystemRoot%\Microsoft.NET\Framework\v4.0.30319

if exist "%Frameworkdc%" goto netOld

:DispError

echo 您的机器上没有安装 .net Framework 4.0,安装即将终止

echo 您的机器上没有安装 .net Framework 4.0,安装即将终止 > UnInstallService.log

goto LastEnd

:netOld

cd %Frameworkdc%

echo 您的机器上安装了相应的.net Framework 4.0,可以安装本服务

echo 您的机器上安装了相应的.net Framework 4.0,可以安装本服务 > UnInstallService.log

echo.

echo. >> UnInstallService.log

echo **************************

echo 停止服务

net stop %servicename% >> UnInstallService.log

echo 清理服务

%Frameworkdc%\Installutil.exe /u %filename% >> UnInstallService.log

echo 清理完毕

echo.

echo***************************

echo 操作结束,可以查看日志文件UnInstallService.log中具体的操作结果。

:LastEnd

pause

rem exit

猜你喜欢

转载自www.cnblogs.com/JueYingHuang/p/9129649.html