网页定时任务windows服务解决方法
在项目中需要后台运行一个定时任务,周期性的触发事件。我使用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 的项目代码包