当前位置:首页 > 技术 > .NET > 正文内容

网页定时任务windows服务解决方法

watrt11个月前 (05-08).NET2750

在项目中需要后台运行一个定时任务,周期性的触发事件。我使用vs2015写了一个简单的服务,事定时访问网址以下是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.Timers;
using System.Threading.Tasks;
using System.Configuration;
using System.Net.Http;

namespace CronService
{
    public partial class Service1 : ServiceBase
    {
        private Timer timer;
        private EventLog eventLog;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (!EventLog.SourceExists("CronServiceSource"))
            {
                EventLog.CreateEventSource("CronServiceSource", "CronServiceLog");
            }
            eventLog = new EventLog();
            eventLog.Source = "CronServiceSource";
            eventLog.Log = "CronServiceLog";

            timer = new Timer();
            timer.Interval = double.Parse(ConfigurationManager.AppSettings["cycle"]) * 1000; // 将配置文件中的周期转换为毫秒
            timer.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
            timer.Enabled = true;
            base.OnStart(null);
            // 启动服务时记录事件
            eventLog.WriteEntry("服务已启动!");
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
            base.OnStop();
            // 停止服务时记录事件
            eventLog.WriteEntry("服务已停止!");
        }
        protected async void OnTimerElapsed(object sender, ElapsedEventArgs e)
        {
            var taskUrl = ConfigurationManager.AppSettings["taskurl"];
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var response = await httpClient.GetAsync(taskUrl);
                    var result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"{DateTime.Now}: 访问 {taskUrl} 成功!响应内容:{result}");

                    // 记录信息到系统日志
                    eventLog.WriteEntry($"访问 {taskUrl} 成功!响应内容:{result}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{DateTime.Now}: 访问 {taskUrl} 失败,失败原因:{ex.Message}");

                // 记录错误到系统日志
                eventLog.WriteEntry($"访问 {taskUrl} 失败,失败原因:{ex.Message}", EventLogEntryType.Error);
            }
        }
    }
}

App.config 配置文件代码

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
  <appSettings>
    <add key="TaskUrl" value="http://localhost:8080/" />
    <add key="Cycle" value="5" />
  </appSettings>
</configuration>

服务安装脚本

InstallUtil CronService.exe

服务卸载脚本

InstallUtil /u CronService.exe

InstallUtil 是.net 框架文件下的文件一般位置在:C:\Windows\Microsoft.NET\Framework\v4.0.30319

CronService.zip  Visual Studio 2015 的项目代码包

分享给朋友:

相关文章

C# 使用串口编程例子

C# 使用串口编程例子

使用C#调用com控件来与ESP32通信 打发用的IDE是:SharpDevelop 5.1/*  * 由SharpDevelop创建。  * 用户: xk100  * 日期: 2023/4/7  * 时间: 11:04  *   * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件  */ using...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。