每天在特定时间执行方法的代码C#(Windows服务)失败 [英] Code for executing method every day at specific time C# (Windows Service) failed

查看:58
本文介绍了每天在特定时间执行方法的代码C#(Windows服务)失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每天下午5点有以下代码来执行Windows服务的方法:

I had this code to execute method of windows service every day at 5am:

MyService ws = new MyService ();

protected override void OnStart(string[] args)
{
    if (serviceHost != null)
    {
        serviceHost.Close();
    }

    serviceHost = new ServiceHost(typeof(MyService));

    serviceHost.Open();
    double TimeOfExecution = 5;

    DateTime now = DateTime.Now;
    DateTime today5am = now.Date.AddHours(TimeOfExecution);
    DateTime next5am = now <= today5am ? today5am : today5am.AddDays(1);

    System.Threading.TimerCallback callback = new System.Threading.TimerCallback(ws.MethodToExecute());

    var timer1 = new System.Threading.Timer(callback, null, next5am - DateTime.Now, TimeSpan.FromHours(24));

 }

我希望服务在接下来的5点以及之后每24小时执行一次.

I expected the Service to execute at next 5 o'clock, and every 24 hours after that.

Method MethodToExecute()确实在当天的5点(或其他指定时间)执行,但第二天执行失败.另外,似乎我是否第一次执行都没关系,但是似乎服务在一段时间后进入睡眠状态并且不执行,所以如果不是凌晨五点到达,而是第二天,它将无法执行.

Method MethodToExecute() did get executed at 5 o'clock (or some other specified time) that day, but next day it failed to execute. Also, it seems that it does not matter if I executed it or not for the first time, but it seems like service goes to sleep after some time and doesn't execute, so if 5 o'clock arrives not at current day, but next day, it will fail to execute.

有人知道什么地方可能出问题吗?

Does anyone have an idea what could be wrong?

推荐答案

GC将收集您的 timer ,因为在 OnStart 方法之后您没有对它的任何引用.

GC will collect your timer since you don't have any references to it after OnStart method.

您只是将其作为局部变量.我希望您知道,一旦JIT声明不再在代码中使用局部变量,就可以对其进行垃圾回收.

You're just having it as a local variable. I hope you know local variables are eligible for garbage collection once JIT says that they are no longer used in code.

修复:只需将 timer 存储在实例变量中,就完成了.

Fix: Just store the timer in a instance variabe, you're done.

private System.Threading.Timer my5AmTimer = null;

protected override void OnStart(string[] args)
{
    //All other code..

   this.my5AmTimer = new System.Threading.Timer(callback, null, next5am - DateTime.Now, TimeSpan.FromHours(24));
}

这篇关于每天在特定时间执行方法的代码C#(Windows服务)失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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