Windows定时服务搭建

1.创建服务:选择Windows服务创建项目

2.添加安装程序,生成对应的服务

             

3.属性设置

4.编写定时服务需要执行的业务

using Common.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace WindowsServiceTest
{
    public partial class Service1 : ServiceBase
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public Service1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            log.Info("===============服务启动==============");

            System.Timers.Timer timer = new System.Timers.Timer();

            timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);

            timer.Interval = 5000; //设置多久执行一次

            timer.Enabled = true;
        }

        /// <summary>
        /// 执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            int count = 0;
            for (int i = 0; i < 5000; i++)
            {
                count++;
            }
           
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        protected override void OnStop()
        {
            log.Info("===============服务停止==============");
        }
    }
}

5.重新生成编译代码

(1)复制文件到项目的DBUG下

(2)服务安装:%~dp0InstallUtil.exe %~dp0WindowsServiceTest.exe

         服务卸载:%~dp0InstallUtil /u %~dp0WindowsServiceTest.exe

         写入txt中,修改后缀名为bat使用管理员身份运行

CMD输入:services.msc打开服务结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值