当前位置: 首页 > news >正文

C# 实现Window服务实现定时发送邮件

网上有很多关于window服务的讲解,本篇文章将以实例为主,解读如何实现WINDOW服务。

 

环境: VS 2008

1,  新建 WINDOW服务

 

【注:删除program.cs,因为在service1.cs中,我们会定义程序的入口,就不再需要该文件】

2,  项目会自动生成service1.cs 文件,该类继承自ServiceBase类,我这里把文件service1.designer.cs文件内容,复制到service1.cs中,并删除designer文件。在该文件中,重写了方法onStart,onStop等方法。

代码如下:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.ComponentModel;

usingSystem.Data;

usingSystem.Diagnostics;

usingSystem.Linq;

usingSystem.ServiceProcess;

usingSystem.Text;

usingSystem.Windows.Forms;

usingSystem.IO;

usingSystem.Net.Mail;

 

namespaceSendeMailService

{

    public partial class Service1 : ServiceBase

    {

        private System.ComponentModel.IContainer components= null;

        private bool servicePaused; //服务停止

        private System.Timers.Timer time; //计时器

        private static readonly stringCurrentPath = Application.StartupPath + "\\";

        public Service1()

        {

            InitializeComponent();

        }

        ///<summary>

        ///进程入口处

        ///</summary>

        static void Main()

        {

            ServiceBase[] myservice= new ServiceBase[] { new Service1() };

            ServiceBase.Run(myservice);

        }

        ///<summary>

        ///开始

        ///</summary>

        ///<paramname="args"></param>

        protected override voidOnStart(string[] args)

        {

            if (servicePaused == false)

            {

                string path = CurrentPath + "start-stop.log";

                if (!File.Exists(path))

                {

                    FileStream create = File.Create(path);

                    create.Close();

                }

                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);

                StreamWriter sw = new StreamWriter(fs);

                sw.WriteLine("TheService is Starting On" + DateTime.Now.ToShortDateString());

                sw.Flush();

                sw.Close();

                fs.Close();

 

                time = new System.Timers.Timer(3000);

                time.Enabled = true;

                time.Elapsed += this.timeout;

                time.Start();

            }

        }

 

        private void timeout(object sender, EventArgs e)

        {

            MailMessage mail = new MailMessage();

            mail.Subject = "主题,如xxx";

            mail.From = new MailAddress("kagen.qiu@xxx.cn", "kagen");

            mail.To.Add(new MailAddress("xxx@xxx.cn", "leo")); //可以添加多个收件人

            mail.CC.Add(new MailAddress("xx@xxx.cn", "kyo")); //抄送

            mail.Body = "测试邮件,请勿回复!!!!";

            mail.BodyEncoding = System.Text.Encoding.UTF8;

            mail.IsBodyHtml = false;

            mail.Priority = MailPriority.High;

 

            SmtpClient smtp = new SmtpClient("smtp.xxxx.com", 25);

            smtp.EnableSsl = true;

            smtp.UseDefaultCredentials = false;

            smtp.Credentials = new System.Net.NetworkCredential("usrname", "password"); //通行证

            smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //递送方法为 网络

            smtp.Send(mail);

        }

        ///<summary>

        ///结束

        ///</summary>

        protected override void OnStop()

        {

            servicePaused = true;

        }

        ///<summary>

        ///暂停服务

        ///</summary>

        protected override void OnPause()

        {

            servicePaused = true;

        }

 

        ///<summary>

        ///恢复服务

        ///</summary>

        protected override void OnContinue()

        {

            servicePaused = false;

        }

        protected override void Dispose(booldisposing)

        {

            if (disposing &&(components != null))

            {

                components.Dispose();

            }

            base.Dispose(disposing);

        }

        private void InitializeComponent()

        {

            components = newSystem.ComponentModel.Container();

            this.ServiceName = "Mailxxxxxxx";

 

            this.CanPauseAndContinue = true;

            this.CanStop = true;

            servicePaused = false;

        }

    }

}

 

 

3,  新建安装文件 SEInstall.cs 继承自 Install

 

4,  service1.cs一样,删除designer.cs文件

代码如下:

using System;

using System.Collections;

using System.Collections.Generic;

using System.ComponentModel;

using System.Configuration.Install;

using System.Linq;

 

 

namespace SendeMailService

{

    [RunInstaller(true)]

    public partialclass SEInstaller : Installer

    {

        privateSystem.ComponentModel.IContainer components= null;

        privateSystem.ServiceProcess.ServiceProcessInstallerspInstaller;

        privateSystem.ServiceProcess.ServiceInstaller sInstaller;

        publicSEInstaller()

        {

           InitializeComponent();

        }

 

 

        ///<summary>

        ///清理所有正在使用的资源。

        ///</summary>

        ///<paramname="disposing">如果应释放托管资源,为 true;否则为 false。</param>

        protectedoverride void Dispose(bool disposing)

        {

            if(disposing && (components != null))

            {

               components.Dispose();

            }

           base.Dispose(disposing);

        }

 

        #region 组件设计器生成的代码

 

        ///<summary>

        ///设计器支持所需的方法 - 不要

        ///使用代码编辑器修改此方法的内容。

        ///</summary>

        privatevoid InitializeComponent()

        {

           components = new System.ComponentModel.Container();

           this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();

           this.sInstaller = new System.ServiceProcess.ServiceInstaller();

            //

            //spInstaller

            //

           this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

           this.spInstaller.Password = null;

           this.spInstaller.Username = null;

            //

            //sInstaller

            //

           this.sInstaller.ServiceName = "Mailxxxxxxx";

           sInstaller.DisplayName = "发送邮件服务";

           sInstaller.Description = "一个定时发送邮件的服务";

           this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;

            //

            //Installer1

            //

           this.Installers.AddRange(new System.Configuration.Install.Installer[] {

           this.spInstaller,

           this.sInstaller});

        }

 

        #endregion

    }

}

5,编译成功之后,我们要将生成的exe文件,安装到【服务】

打开CMD-右击【管理员身份运行】-

将路径定位到上图目录下:

定位方式: 1, cd.. 2, cd .. 3,cd C:\Windows\Microsoft.NET\Framework\v2.0.50727

输入如下命令:installutil path[注:pathEXE文件所在目录]

installutile:\xxx.exe

DOS界面会有提示,如果成功,则在【服务】列表会有提示

6,  测试设定的邮箱是否接收到邮件,即可判定是否成功!

7,  卸载服务:Installutil /u path

【注:如果卸载不成功,可以进入注册表删除对应的服务即可。】

services下面找到对应的服务,删除即可。

 

【注:如果服务不能启动,说明程序有问题。可以将编写的程序,先放到 WINFORM程序中测试下】

 

 

 

 

相关文章:

  • Access denied for user 'root'@'localhost' (using password:YES) 解决方案
  • Maximum request length exceeded
  • C# 计时器Timer控件,倒计时
  • MySQL 错误Incorrect key file for table ******.MYI; try to repair it的解决
  • 关于无效使用 Null: 'Replace'
  • css透明与半透明
  • C# FTP上传文件至服务器代码
  • 利用FTPClient类实现文件的上传下载功能
  • mysql不能使用innodb存储引擎
  • ASP.NET MVC3 异常处理
  • 解决【Unable to make the session state request to the session state server】
  • 如何在IIS里对网站限速
  • msxml3.dll 错误 '80072efd' A connection with the server could not be established
  • 解决IE6浏览器中Div层挡不住Select组件
  • 解决IE6下select z-index 无效
  • 2019.2.20 c++ 知识梳理
  • JavaScript DOM 10 - 滚动
  • Java多态
  • Java方法详解
  • Node.js 新计划:使用 V8 snapshot 将启动速度提升 8 倍
  • React组件设计模式(一)
  • SAP云平台里Global Account和Sub Account的关系
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • Terraform入门 - 3. 变更基础设施
  • ViewService——一种保证客户端与服务端同步的方法
  • 闭包--闭包作用之保存(一)
  • 给Prometheus造假数据的方法
  • 码农张的Bug人生 - 初来乍到
  • 前端性能优化--懒加载和预加载
  • 使用权重正则化较少模型过拟合
  • 算法-插入排序
  • 我的zsh配置, 2019最新方案
  • 你对linux中grep命令知道多少?
  • #大学#套接字
  • (C语言版)链表(三)——实现双向链表创建、删除、插入、释放内存等简单操作...
  • (附源码)springboot炼糖厂地磅全自动控制系统 毕业设计 341357
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (黑马出品_高级篇_01)SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式
  • (机器学习-深度学习快速入门)第一章第一节:Python环境和数据分析
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (四)Android布局类型(线性布局LinearLayout)
  • (一)【Jmeter】JDK及Jmeter的安装部署及简单配置
  • (已解决)报错:Could not load the Qt platform plugin “xcb“
  • (转)h264中avc和flv数据的解析
  • (转)清华学霸演讲稿:永远不要说你已经尽力了
  • .NET delegate 委托 、 Event 事件
  • .net refrector
  • .net(C#)中String.Format如何使用
  • .Net7 环境安装配置
  • .net和jar包windows服务部署
  • .Net中ListT 泛型转成DataTable、DataSet
  • @EnableAsync和@Async开始异步任务支持
  • @transactional 方法执行完再commit_当@Transactional遇到@CacheEvict,你的代码是不是有bug!...
  • [c]扫雷
  • [C++] 默认构造函数、参数化构造函数、拷贝构造函数、移动构造函数及其使用案例