Windows 服务在指定时间运行功能 [英] Windows Service to run a function at specified time

查看:29
本文介绍了Windows 服务在指定时间运行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启动一个 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 上,如果当前间隔不是 24 小时,则将 _timer.Interval 重置为 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;
    }  
}

有时人们希望将服务安排在 0 天开始,而不是明天,所以他们更改了 DateTime.Today.AddDays(0).如果他们这样做并设置过去的一次它会导致将 Interval 设置为负数的错误.

Sometimes people want to schedule the service to start at day 0, not tomorrow so they change DateTime.Today.AddDays(0).If they do that and set a time in the past it causes an error setting the Interval with a negative number.

//Test if its a time in the past and protect setting _timer.Interval with a negative number which causes an error.
double tillNextInterval = _scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
if (tillNextInterval < 0) tillNextInterval += new TimeSpan(24, 0, 0).TotalSeconds * 1000;
_timer.Interval = tillNextInterval;

这篇关于Windows 服务在指定时间运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆