首次成功运行后,Windows服务无法启动

时间:2013-09-23 13:54:35

标签: c# windows-services

我创建了一个Windows服务,它会根据某些条件向用户发送邮件。 我把它安装在自动模式的服务器上。从日志中我可以看到它第一次成功运行并结束。

之后我没有看到它在日志中再次运行。

我在管理工具中检查了该服务,并说它已启动。

我也重启了服务但没有用,它没有重新启动。

以下是我用来启动服务的代码。

public partial class ScheduledService : ServiceBase
{
    Timer timer;
    private DateTime lastRun = DateTime.Now;
    private DateTime DailyRunTime = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["DailyRunTime"]);
    public ScheduledService()
    {
        InitializeComponent();
        //GetDocRetentionList DocList = new GetDocRetentionList();
        //DocList.GetDataSet();
    }

    protected override void OnStart(string[] args)
    {
        //System.Diagnostics.Debugger.Launch();
        TraceService("start service");
        //timer = new Timer(24 * 60 * 60 * 1000);
        timer = new Timer(10 * 60 * 1000);
        timer.Start();
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        double TimerInterval = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["Timer"]);
        timer.Interval = TimerInterval;
        timer.Enabled = true;
    }

    protected override void OnStop()
    {
        timer.Enabled = false;
        TraceService("stopping service");
    }

    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        TraceService("Service started at " + DateTime.Now);
        if (lastRun.Date < DateTime.Now.Date)
        {
            if (DateTime.Now > DailyRunTime)
            {
                GetDocRetentionList DocList = new GetDocRetentionList();
                DocList.GetDataSet();
                timer.Stop();
                lastRun = DateTime.Now.Date;
                //timer.Start();
            }
        }

    }

在这方面我能得到的任何帮助都会非常有帮助。 Plz让我知道。

1 个答案:

答案 0 :(得分:2)

嗯..你的服务被设置为执行一次,然后它在OnElapsedTime方法中关闭了计时器,但从未重新开启。

OnElapsedTime应该做的第一件事是关闭计时器。它应该做的最后一件事是重新开启。

相关问题