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

查看:19
本文介绍了每天在特定时间执行方法的代码 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 点(或其他指定时间)执行了,但第二天它没有执行.另外,我第一次执行与否似乎无关紧要,但似乎服务在一段时间后进入睡眠状态并且不执行,因此如果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天全站免登陆