创建windows services 实现定时操作 提供调试方法

1.VS-》文件-》新建项目,弹出窗口中选择Visual C#-》windows-》windows服务 

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.IO;
using System.Timers;
using System.Runtime.InteropServices;
using System.Data.SqlClient;
using System.Net.Mail;

namespace TimedTask
{
    public partial class Service1 : ServiceBase
    {
        Timer timer;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer = new Timer(60000);//1000=1s,此处为1分钟
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        protected override void OnStop()
        {
            timer.Stop();
            timer.Dispose();
        }

        //定时执行的任务
        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            string time = DateTime.Now.AddDays(1).ToShortDateString() + " " + DateTime.Now.ToLongTimeString().ToString();

            string filePath = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
            StreamWriter sw = null;
            if (!File.Exists(filePath))
            {
                sw = File.CreateText(filePath);
            }
            else
            {
                sw = File.AppendText(filePath);
            }
            sw.Write("访问时间:" + time + Environment.NewLine);
            sw.Close();
        }        
        
    }
}
3.生成工程,在bin目录下会生成exe文件 

4.向系统添加该服务: 
(1).找到系统盘下的.net路径:本机是C:\Windows\Microsoft.NET\Framework\v4.0.30319,找到其中的InstallUtil.exe 
(2).找到工程文件路径下的bin\Debug\项目名称.exe 
(3).打开命令行工具,输入:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe空格D:\WebSites\TimedTask\bin\Debug\项目名称.exe  
执行成功后,会在Windows的服务中,出现了刚刚添加的服务的名称。 
注意:中文字符空格是表示敲击空格键。 

5.启动该服务即可。 

6.调试: 
服务已启动时,在VS中选择调试-》附加到进程,可找到该服务名称,附加即可调试。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值