C# 自定义window服务,实现定时任务

一、自定义WIndows服务

1.新建一个Windows服务(.NET Framework)项目
在这里插入图片描述
2.输入项目名称,选择安装位置,,选择安装框架版本;创建。
在这里插入图片描述
3.找到MyService.cs ,右击‘查看代码’在这里插入图片描述
添加如下代码

public partial class MyService : ServiceBase
    {
        string path = "WarmService";
        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            CommonHelper.WriteLog("=============服务启动=============", path);
            JobManager.Initialize(new MyRegistry());//注册定时任务模块
            CommonHelper.WriteLog("=============服务注册成功=============", path);
        }

        protected override void OnStop()
        {
            CommonHelper.WriteLog("=============服务停止=============", path);
        }
    }

4.双击MyService.cs,在出现的界面中右击–>选择“添加安装程序”。
在这里插入图片描述
点击后,会自动生产连个控件,sericcelnstaller1 和sericeProcessInstaller1
在这里插入图片描述
5.分别设置两个控件的属性
在这里插入图片描述
在这里插入图片描述
6.生成项目;
7.在同一个解决方案中,新增一个Windows From应用程序项目;
在这里插入图片描述
8.找到form1窗体
在这里插入图片描述
9.在Windows From应用程序项目里面引用Windows服务(.NET Framework)项目文件
在这里插入图片描述
10.form1各按钮的实现代码如下

 string serviceFilePath = string.Format(@"{0}\\WarmService.exe", Application.StartupPath);
        string serviceName = "WarmService";
        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
            MessageBox.Show("启动服务成功");
            button3.Enabled = false;
            button4.Enabled = true;         
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
            this.InstallService(serviceFilePath);
            MessageBox.Show("安装服务成功");
            button1.Enabled = false;
            button2.Enabled = true;
            button3.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
            }
            MessageBox.Show("卸载服务成功");
            button2.Enabled = false;
            button1.Enabled = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
            MessageBox.Show("停止服务成功");
            button4.Enabled = false;
            button3.Enabled = true;
        }
        //判断服务是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }
        //安装服务
        private void InstallService(string serviceFilePath)
        {
            //CommonHelper.LanXinInfo("N0811051", "测试信息");
            //return;
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }
        //卸载服务
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        //启动服务
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }
        //停止服务
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
        }

以上自定义WIndows服务完成
二、自定义定时任务,并把定时任务挂到自定义的windows服务里面执行

  1. 在windows服务项目中添加FluentScheduler引用,FluentScheduler 中 对象: IJob(工作)、Registry(注册)、Schedule(计划)
    在这里插入图片描述
    2.在在windows服务项目中定义定时任务在这里插入图片描述
    定时任务基本架构如下
public class JobJcGlueWaterShelfExpire : IJob
    {
        void IJob.Execute()
        {   
            this.JsShelfExpireWarn("CONN_JM_TEST");        
        }
        public void JsShelfExpireWarn(string conStr)
        {
           //定时任务实现的业务逻辑
        }
    }    

3.编写一个注册表。继承Registry类,用于调用定时任务

 public class MyRegistry : Registry
    {
        public MyRegistry()
        {
            #region 定时任务注册;          
            //明天上午9点,自动执行定时任务A  
            Schedule<定时任务A>().NonReentrant().ToRunNow().AndEvery(1).Days().At(9, 00);
            
            // 每5秒执行一次(指定一个时间间隔运行,根据自己需求,可以是秒、分、时、天、月、年等。)
            Schedule<定时任务A>().ToRunNow().AndEvery(5).Seconds();
            // 每两秒执行一次
             Schedule<定时任务A>().ToRunNow().AndEvery(2).Seconds();Hours()//每天10点先执行定时任务A,再执行定时任务B;
            Schedule<定时任务A>().AndThen<定时任务B>().NonReentrant().ToRunNow().AndEvery(1).Days().At(10, 00);
            #endregion
        }
    }
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C# 中添加 Windows 服务,你需要使用 System.ServiceProcess 命名空间中的 ServiceBase 类。下面是一个简单的示例,演示如何创建一个 Windows 服务,并将其安装到计算机上: 首先,创建一个新的 C# 项目并添加一个新的类文件。在类文件中,定义一个类,继承自 ServiceBase 类,并重写 OnStart 和 OnStop 方法: ```csharp using System.ServiceProcess; namespace MyService { public partial class MyService : ServiceBase { public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { // 在此处启动服务 } protected override void OnStop() { // 在此处停止服务 } } } ``` 在 OnStart 方法中,写下你想要在服务启动时执行的代码。在 OnStop 方法中,写下你想要在服务停止时执行的代码。 然后,打开项目属性,选择“应用程序”选项卡,并将输出类型设置为“Windows 应用程序”。这将使项目生成为可安装的 Windows 服务。 接下来,你需要编写一些代码来安装和卸载服务。可以使用 System.Configuration.Install 命名空间中的 InstallUtil 工具来执行这些操作。在项目中添加一个新的安装程序类,如下所示: ```csharp using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; [RunInstaller(true)] public class MyServiceInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public MyServiceInstaller() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); // 设置服务的名称和显示名称 serviceInstaller.ServiceName = "MyService"; serviceInstaller.DisplayName = "My Service"; // 设置服务的启动类型为自动 serviceInstaller.StartType = ServiceStartMode.Automatic; // 将服务安装程序和进程安装程序添加到安装程序集合中 Installers.Add(serviceInstaller); Installers.Add(processInstaller); } } ``` 在这个类中,你需要设置服务的名称、显示名称和启动类型。在 Installers 集合中添加 ServiceInstaller 和 ServiceProcessInstaller 对象,以便安装程序可以正确地安装和卸载服务。 最后,在 Visual Studio 中打开“命令提示符”窗口,并导航到项目的输出目录。运行以下命令安装服务: ```bat installutil MyService.exe ``` 运行以下命令卸载服务: ```bat installutil /u MyService.exe ``` 这些命令将使用 InstallUtil 工具来安装和卸载服务。注意,需要使用管理员权限运行命令提示符窗口,才能正确执行这些命令。 希望这个简单的示例可以帮助你开始编写自己的 Windows 服务

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值