您好,欢迎来到花图问答。
搜索
您的当前位置:首页使用 WindowsService 轻松解决定时任务问题

使用 WindowsService 轻松解决定时任务问题

来源:花图问答

一、前言

开发中经常会遇到需要在某个特定时间(定时),去处理某些事情的业务需求。通常 。常用的有 Timer 和 是一个Java开源的作业调度框架,后面才移植到 平台上面,在配置文件中简单配置就可以实现作业调度功能。而 Timer 的使用更加简单,如果是在项目中的话,直接在 Application_Start 调用即可。今天我们这两种种方式都不做介绍。我们来研究一下作为系统服务运行的作业调度。

二、WindowsServer

顾名思义,在 Windows 系统下的服务。如下图:

系统服务

下面我们来看看怎样开发 WindowsService

1.WindowsService 创建项目

创建项目

2.右键查看代码 或者 F7

查看代码

3.添加代码

创建 Timer 对象

    System.Timers.Timer time;


设置定时器属性

    protected override void OnStart(string[] args)
    {
        time = new System.Timers.Timer();
        EventLog.WriteEntry("***我是描述****");
        time.Interval = 1000 * 60 * 60;//执行间隔....每小时执行
        time.AutoReset = true;//设置是执行一次(false)还是一直执行(true);    
        time.Elapsed += new System.Timers.ElapsedEventHandler(MyEvent);//利用委托执行方法
        time.Enabled = true;//开启定时器
    }

结束关闭定时器

    protected override void OnStop()
    {
        this.time.Enabled = false;
    }

4.业务代码,笔者是需要自动掉某个API,代码如下,仅供参考

    public void MyEvent(object sender, System.Timers.ElapsedEventArgs e)
    {
        string postData = string.Empty;
         request = 
        System.IO.Stream requestStream = default(System.IO.Stream);
        byte[] postBytes = null;
        string url = 
        request = 
        request.ContentType = 
        request.ContentLength = postData.Length;
        request.Timeout = 10000;
        request.Method = "POST";
        request.AllowAutoRedirect = false;
        requestStream = request.GetRequestStream();
        postBytes = System.Text.Encoding.ASCII.GetBytes(postData.ToString());
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();
    }

注意实际应用上要进行验证,API是否为合法调用

三、WindowsService 的发布和安装

1.添加安装程序

添加安装程序

2.设置 Account

设置 Account

3.设置 服务名称(根据自己需求)

设置服务名称

4.生成项目,在 ~/bin/debug/ 中找到我们的服务可执行文件 “项目名.exe”

生成项目

5.安装服务的命令

1.管理员权限运行命令行工具

cd 
cd  

2.安装服务。注意后面的路径就是我们可执行文件的存放路径

InstallUtil "D:\ZDFService.exe"

6.安装成功

安装成功

7.启动服务

启动服务

8.卸载

InstallUtil /u "D:\ZDFService.exe"

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务