C# 创建windows服务并定时执行

一、创建window服务

1、新建项目–>选择Windows服务。默认生成文件包括Program.cs,Service1.cs

2、在Service1.cs添加如下代码:

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 Service1
{
    partial class Service1: ServiceBase
    {
        System.Timers.Timer _Timer;  //计时器
        private static object _LockSMS_Send = new object();
        public GGGoodsRack()
        {
            InitializeComponent();
        }
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            int minute = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["GapDate"].ToString());
            this._Timer = new System.Timers.Timer();
            this._Timer.Interval = minute * 60 * 1000;  //设置计时器事件间隔执行时间
            this._Timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
            this._Timer.Enabled = true;
        }
        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            this._Timer.Enabled = false;
        }
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Log.Read(DateTime.Now.ToString("-----------------------------------时 间:yyyy-MM-dd HH:mm:ss------------------------------------"));
            DateTime t1 = DateTime.Now;
            Log.Read(" ");
            Log.Read(string.Format("执行时间:{0}分{1}秒", (DateTime.Now - t1).Minutes, (DateTime.Now - t1).Seconds));
            Log.Read(" ");
        }
    }
}

二、添加window服务安装程序

1、打开Service1.cs【设计】页面,点击右键,选择【添加安装程序】,会出现serviceInstaller1和serviceProcessInstaller1两个组件

2、将serviceProcessInstaller1的Account属性设为【LocalSystem】, serviceInstaller1的StartType属性设为【Automatic】,ServiceName属性可设置服务名称,此后在【管理工具】–》【服务】中即显示此名称

3、ProjectInstaller.cs文件,在安装服务后一般还需手动启动(即使上述StartType属性设为【Automatic】),可在ProjectInstaller.cs添加如下代码实现安装后自动启动

public ProjectInstaller()
{
    InitializeComponent();
    this.Committed += new InstallEventHandler(ProjectInstaller_Committed);   
}

private void ProjectInstaller_Committed(object sender, InstallEventArgs e)
{
    //参数为服务的名字
    System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服务名称");
    controller.Start();
}   

三、安装、卸载window服务

1、输入cmd(命令行),输入cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319,2.0为cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

2、安装服务(项目生成的exe文件路径)

InstallUtil “E:\WindowsService1\bin\Debug\WindowsService1.exe”

3、卸载服务

InstallUtil /u “E:\WindowsService1\bin\Debug\WindowsService1.exe”

四、查看window服务

控制面板–>管理工具–>服务,可在此手动启动,停止服务

五、调试window服务

1、通过【事件查看器】查看

2、直接在程序中调试(菜单–>调试–>附加进程–>服务名(这里的服务名是项目名称,不是ServiceName属性自定义的名称,所以建议自定义名称和项目名称保持一致,另外需勾选【显示所有用户的进程】才能看到服务名)–>附加

  1. 在程序中打断点调试即可,另外调试服务时服务必须已启动(管理工具–>服务)
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用C#编写一个Windows服务定时执行任务。下面是一个简单的示例: 首先,创建一个新的C#项目,并选择“Windows服务”模板。 然后,在你的服务类中,你可以使用`System.Timers.Timer`类来执行定时任务。在服务的`OnStart`方法中初始化定时器,并设置间隔时间和要执行的方法。在`OnStop`方法中停止定时器。 这是一个基本的示例代码: ```csharp using System; using System.ServiceProcess; using System.Timers; namespace YourNamespace { public partial class YourService : ServiceBase { private Timer timer; public YourService() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(); timer.Interval = 60000; // 1 minute in milliseconds timer.Elapsed += TimerElapsed; timer.Start(); } protected override void OnStop() { timer.Stop(); timer.Dispose(); } private void TimerElapsed(object sender, ElapsedEventArgs e) { // 执行你的定时任务 } } } ``` 请注意,上面的代码将每隔1分钟执行一次`TimerElapsed`方法。你可以根据需要更改间隔时间。 一旦你完成了代码编写,你可以将你的项目编译为一个可执行文件,然后使用`installutil`命令行工具来安装和启动服务。例如,打开命令提示符,导航到你的可执行文件所在的文件夹,并运行以下命令: ``` installutil YourService.exe ``` 这将安装你的服务,并可以使用服务管理器启动、停止和管理它。 希望这可以帮助到你开始编写一个定时执行Windows服务!如有任何问题,欢迎继续提问。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值