首页 > 系统相关 >执行定时任务:使用Windows service创建定时器

执行定时任务:使用Windows service创建定时器

时间:2022-10-11 09:45:57浏览次数:69  
标签:定时器 Service service Windows System new message TimerService

一、需求

创建一个定时任务,定时执行数据处理任务,并记录日志,发送邮件。本篇使用的方法:windows service 

定时任务常用的实现方法可参考大佬文章:Windows 自动定时执行任务的几种实现方法

 

二、实现

1、打开VS新建一个windows Service程序,我命名为TimerService

注意:.NET Framwork框架的选择要与你电脑上的框架一致,我这里选择的是4.7.2

 

2、在Service1设计器中右击空白处选择查看代码

 

 

 

3.在Service1.cs中设定
Onstart方法定义定时器的开始执行,执行的时间间隔,以及时间间隔达到后所要执行的方法。

执行了一个文件写入任务,代码如下:

using System;
using System.IO;
using System.Net.Mail;
using System.ServiceProcess;
using System.Timers;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace TimerService
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer;

        public Service1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Start Service
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            timer = new Timer(60 * 1000);
            timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            timer.Start();
            WriteLog("Service Start." + "  " + DateTime.Now.ToString());
        }

        /// <summary>
        /// Stop Service
        /// </summary>
        protected override void OnStop()
        {
            WriteLog("Service Stop." + "  " + DateTime.Now.ToString());

            timer.Stop();
            timer.Dispose();
        }

        /// <summary>
        /// Execute Service
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            WriteLog("Service Execute……" + "  " + DateTime.Now.ToString());

            var res = Send();
            WriteLog(res);
        }

        /// <summary>
        /// Write Log
        /// </summary>
        /// <param name="str"></param>
        protected void WriteLog(string str)
        {
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
            StreamWriter sw = null;
            if (!File.Exists(filePath))
            {
                sw = File.CreateText(filePath);
            }
            else
            {
                sw = File.AppendText(filePath);
            }
            sw.Write(str + Environment.NewLine);
            sw.Close();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="body"></param>
        public string Send()
        {
            try
            {
                SmtpClient client = new SmtpClient("smtp.wdc.com", 25);
                client.UseDefaultCredentials = true;

                MailAddress from = new MailAddress("[email protected]");
                MailAddress to = new MailAddress("[email protected]");
                MailAddress cc = new MailAddress("[email protected]");

                MailMessage message = new MailMessage();

                message.From = from;
                message.To.Add(to);
                message.CC.Add(cc);
                //message.Attachments.Add(new Attachment("test.txt"));
                message.Body = "大家好,blablablabla邮件正文";
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = "邮件标题";
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                client.Send(message);
                message.Dispose();
                message = null;
                client.Dispose();
                client = null;

                return "发送正常";
            }
            catch (Exception e)
            {
                return "异常:" + e.Message;
            }
        }
    }
}

 

 

4、在Service1设计器中右击空白处,选择添加安装程序,会添加一个ProjectInstaller设计器

 

 

 

 

5、在ProjectInstaller设计器中选择serviceProcessInstaller,右击查看属性,将Account的值改为LocalSystem

 

 

 

 

6、在ProjectInstaller设计器中选择serviceInstaller1,右击查看属性,ServiceName就是服务中显示的名称,将其命名TimerService

 

 

 

 

7、右击解决方案,点击生成解决方案

 

 

三、安装
1、打开刚刚新建项目所在的文件夹,找到bin文件下面的debug文件夹,比如:C:\Users\Administrator\Source\Repos\TimerService\bin\debug,里面有个TimerService.exe应用程序,就是我们所要执行的项目

 

2、打开文件夹C:\Windows\Microsoft.NET\Framework\v4.0.30319,可以看到里面有一个InstallUtil.exe的应用程序,这就是我们要的安装工具,这里的Framework的版本与我们项目的Framework版本保持一致

 

3、打开cmd输入cd C:\Users\Administrator\Source\Repos\TimerService\bin\Debug指令,

然后再输入C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /i TimerService.exe,即可完成安装。

PS:需要注意,cmd需要以管理员身份运行,否则可能出现安装失败的情况(提示权限不足,如下图2)

 

安装失败提示: 

 

 


4、启动任务管理器,点击服务,找到名称TemrService的服务,右击启动,即可将创建的定时服务启动,这里的服务名称就是我们在项目的serviceInstaller1的属性里面设置的serviceName

 

 

 

5、在我们的C:\Users\Administrator\Source\Repos\TimerService\bin\Debug文件下面会发现多了一个log.txt的文件,就是我们在项目中创建的日志文件,打开即可看到项目正常执行。

 

 

 

 

四、卸载
卸载服务需要在cmd中输入以下指令即可

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /u TimerService.exe

 

 

 

参考原文链接:https://blog.csdn.net/qingyou2006/article/details/126464305

Windows 自动定时执行任务的几种实现方法

标签:定时器,Service,service,Windows,System,new,message,TimerService
From: https://www.cnblogs.com/Yan3399/p/16778170.html

相关文章

  • windows 常用命令
    find命令:netstat-an|find"443"  查看路由route  print添加一条路由routeadd  目标IP  mask255.255.255.255下一跳IP-p删除路由routedelete10.10......
  • system.threading.timer 开启与停止 windows服务 定时任务
    system.threading.timer开启与停止Threading.Timer属于100%多线程Timers.Timer默认多线程,可设置为单线程既然是多线程,不管通过回调还是事件执行任务,都是开启的另......
  • 郁金香 用C写一个定时器来循环获取阳光
    先来张效果图定时器代码 HWND游戏窗口句柄=FindWindowA("MainWindow","植物大战僵尸中文版");::SetTimer(游戏窗口句柄,4567,UINT_PTR(1000),阳光回调)......
  • 为什么要分为service层,dao层,controller层?
        开发中有感而想,然后查了一下,发现这个观点不错,以后开发尽量业务代码还是写在service层,然后controller层简单点,看起来也清晰。首先,分三层并不仅仅是java的......
  • firewalld关于service的操作
    ####service就是zone下面的一个子单元,也就是一个指定的端口,因为防火墙就是针对某一个端口做一些限制,比如http操作的80端口,https操作的是443端口,ssh操作的是22端口#firewal......
  • k8s--service 之 HeadLiness、NodePort 使用
    前戏环境还是使用我们上节的环境:https://www.cnblogs.com/zouzou-busy/p/16156384.htmlHeadLiness在某些场景中,开发人员可能不想使用Service提供的负载均衡功能,而希望......
  • 找不到虚拟机监控程序,请启用虚拟机监控程序支持(打开Windows Sandbox提示)
      本机安装了VM,所以为支持VM对系统做了些配置。具体原因是因为兼容性问题。上述解决办法:1、确保沙盒和监控程序功能启用 2、在 WindowsPowershell(管理员) 中执行......
  • 常用windows快捷键大全
    简要要将电脑玩的溜,快捷键是必须要掌握的技能,本文汇总了一些常用的快捷键,相信加以练习,一定能提高你的工作效率。笔者将常用快捷键分为四个系列,如下所示:Win系列Ctrl......
  • Windows域的管理
    目录​​域的管理​​​​默认容器​​​​组织单位的管理​​​​添加额外域控制器​​​​卸载域控服务器​​​​组策略应用​​域的管理域用户账户的管理创建域用户账......
  • windows已找到设备的驱动程序软件... 但系统策略禁止安装此设备
    1、Windows10系统,插上摄像头弹出系统策略禁止安装此设备,请与系统管理员联系的通知。2、系统也进行了摄像头的安装,但最后显示,设备安装不完整的错误提示框:无法安装设备。你可......