如何从 Windows 服务启动计时器方法? [英] How to start method on timer from windows service?

查看:36
本文介绍了如何从 Windows 服务启动计时器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以在大约 10 分钟内执行.它本身就很顺利.我需要每小时使用 Windows 服务启动此方法(这是强制性的).所以我通过一些例子编写了我的服务(只有一个调用开始):

I have a method that executes in about 10 minutes. And it goes well just by itself. I need to start this method every hour using windows service (this is obligatory). So I've written my service by some examples (just one invoke for start):

partial class ServiceWSDRun : ServiceBase
{
    protected override void OnStart(string[] args)
    {
        Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
        t.Start();
    }
}

现在,当我安装它时,它会在一个新线程中启动我的方法,但该线程似乎以 OnStart() 结束 - 它实际上从 me 方法的开头记录了一些信息.为什么它会停止,我该怎么办?

Now when I install it, it launches my method in a new thread but this thread seem to end with the OnStart() - it actually logs some info from the beginning of me method. Why does it stop and what should I do?

我想最后我应该有这样的东西:

And I'm thinking in the end I should have something like this:

partial class ServiceWSDRun : ServiceBase
{
    System.Timers.Timer timer = null;

    protected override void OnStart(string[] args)
    {
        Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
        t.Start();

        timer = new System.Timers.Timer();
        timer.Interval = 60 * 60 * 1000; // 1 hour
        timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
        timer.Enabled = true;
    }

    public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
    {
        WebServiceDownload.MainProgram.Execute();
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
    }
}

我如何使它工作?请记住,该方法需要大约 10 分钟才能执行.

How do I make it work? And keep in mind that method takes ~10 mins to execute.

推荐答案

你应该使用 System.Threading.Timer 而不是 System.Timers.Timer.

You should use System.Threading.Timer instead of System.Timers.Timer.

这里是参考:

https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx

另外,关于同一主题的另一个线程:

Also, another thread about the same topic:

System.Timers.Timer 与 System.Threading.Timer

您应该锁定执行,避免在第一次执行完成之前进行第二次执行.

You should lock the execution, avoiding the second execution before the first one finishes.

这篇关于如何从 Windows 服务启动计时器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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