C# 如何在特定时间运行服务?

C# 如何在特定时间运行服务?,c#,web-services,timer,C#,Web Services,Timer,我有一个服务,目前我相信是运行每10分钟,但我希望它运行在每天晚上7点,我需要改变什么 private Timer _timer; private DateTime _lastRun = DateTime.Now; protected override void OnStart(string[] args) { _timer = new Timer(10 * 60 * 1000); // every 10 minutes?? _time

我有一个服务,目前我相信是运行每10分钟,但我希望它运行在每天晚上7点,我需要改变什么

 private Timer _timer;
    private DateTime _lastRun = DateTime.Now;

    protected override void OnStart(string[] args)
    {
        _timer = new Timer(10 * 60 * 1000); // every 10 minutes??
        _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {

        if (_lastRun.Date < DateTime.Now.Date)
        {
            // stop the timer 
            _timer.Stop();               

            try
            {
                SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
                test.Import();
            }
            catch (Exception ex) { }

            _lastRun = DateTime.Now;
            _timer.Start();
        }
    }
private Timer\u Timer;
private DateTime\u lastRun=DateTime.Now;
启动时受保护的覆盖无效(字符串[]args)
{
_定时器=新定时器(10*60*1000);//每10分钟一次??
_timer.appeated+=新系统.Timers.ElapsedEventHandler(timer_appeated);
}
私有无效计时器(对象发送器,System.Timers.ElapsedEventArgs e)
{
如果(_lastRun.Date
Windows服务是一项持续运行的任务。如果要查找需要在指定时间运行的内容,请编写一个

替换:

if (_lastRun.Date < DateTime.Now.Date)
{
}
if(_lastRun.Date
与:

DateTime startAt=DateTime.Today.AddHours(19);
如果(_lastRun=startAt)
{
}

可能会成功。但是我更喜欢使用已经建议过的计划任务

为什么要使用服务来完成这项任务?将其设置为计划任务。因此,您将接受的答案粘贴到一个新问题中,而不是在下面查看投票最多的答案。这有7个小时吗?不是每天晚上7点吗?@初学者:实际上它每天早上7点就这么做了,不过我现在已经改了。请注意,
DateTime.Today
获取0小时的当前日期,然后我们添加19小时,使之成为晚上7点进行比较。然后我们检查两件事。。首先,如果它在计划时间之后没有运行。然后,我们确保预定的时间是过去的
DateTime startAt = DateTime.Today.AddHours(19);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
}