Windows服务运行在指定的时间函数 [英] Windows Service to run a function at specified time
问题描述
我想开始一个Windows服务在特定时间运行的日常功能。
I wanted to start a Windows service to run a function everyday at specific time.
用什么方法,我应该考虑实现这个?定时器或使用线程?
What method i should consider to implement this? Timer or using threads?
推荐答案
(1)第一次启动时,设置_timer.Interval以毫秒为单位的服务开始之间的用量并安排一个时间。此示例设置计划时间上午7:00为_scheduleTime = DateTime.Today.AddDays(1).AddHours(7);
(1) On first start, Set _timer.Interval to the amount of milliseconds between the service start and schedule time. This sample set schedule time to 7:00 a.m. as _scheduleTime = DateTime.Today.AddDays(1).AddHours(7);
(2)在Timer_Elapsed,复位_timer.Interval至24小时(以毫秒为单位)如当前间隔不是24小时。
(2) On Timer_Elapsed, reset _timer.Interval to 24 hours (in milliseconds) if current interval is not 24 hours.
System.Timers.Timer _timer;
DateTime _scheduleTime;
public WinService()
{
InitializeComponent();
_timer = new System.Timers.Timer();
_scheduleTime = DateTime.Today.AddDays(1).AddHours(7); // Schedule to run once a day at 7:00 a.m.
}
protected override void OnStart(string[] args)
{
// For first time, set amount of seconds between current time and schedule time
_timer.Enabled = true;
_timer.Interval = _scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
}
protected void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// 1. Process Schedule Task
// ----------------------------------
// Add code to Process your task here
// ----------------------------------
// 2. If tick for the first time, reset next run to every 24 hours
if (_timer.Interval != 24 * 60 * 60 * 1000)
{
_timer.Interval = 24 * 60 * 60 * 1000;
}
}
这篇关于Windows服务运行在指定的时间函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!