Windows 服务中的错误计时器 [英] Bad timer in Windows service

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

问题描述

我的 Windows 服务中有计时器,但是 Windows 服务没有做它应该做的事情..我想问你,我有没有好的定时器代码?

i have timer in my windows service, but the windows service does not do what it should do.. I want ask you, if i have good code with timer?

我的部分代码(更新):

Part of my code (updated):

protected override void OnStart(string[] args)
{
    timer = new System.Timers.Timer();
    timer.Elapsed += new ElapsedEventHandler(getFileList);
    timer.Interval = 10000;
    timer.Enabled = true;
    timer.AutoReset = false;
}

private void getFileList(object sender, EventArgs e)
{
    //Work with xml...                
    DeleteOldBackupFiles();
}

private void DeleteOldBackupFiles()
{
    string[] Oldfiles = Directory.GetFiles(backup);
    foreach (string Ofile in Oldfiles)
    {
        FileInfo fi = new FileInfo(Ofile);
        if (fi.LastWriteTime < DateTime.Now.AddMonths(-2))
        {
            fi.Delete();
        }
    }
}

根据你的想法,我编辑了我的代码,但结果是一样的..

After your ideas i edit my code, but result is the same..

protected override void OnStart(string[] args)
{
    timer = new System.Timers.Timer();
    timer.Elapsed += new ElapsedEventHandler(getFileList);
    timer.Interval = 10000;
    timer.Enabled = true;
    timer.AutoReset = true;
}

推荐答案

您很可能在计时器的某处发生错误,导致它抛出异常.您不会检测到这一点,因为 System.Timers.Timer 会默默地忽略所有未处理的异常.

You have most likely an error somewhere in your timer making it throw an exception. You will not detect that since System.Timers.Timer silently ignores all unhandled exceptions.

因此,您必须使用 try/catch 块包装所有代码:

You'll therefore have to wrap all code with a try/catch block:

private void getFileList(object sender, EventArgs e)
{
     try
     {
         DeleteOldBackupFiles();
     }
     catch (Exception ex)
     {
         //log exception or just put a breakpoint here.
     }
}

因此您的计时器正在工作,但您做错了.

Hence your timer is working, but you are doing something wrong in it.

这篇关于Windows 服务中的错误计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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