Windows Server计时器无法启动 [英] Windows server timer can not be fire

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

问题描述

大家好,

计时器代码中的以下代码无法在Windows Service中工作.任何人都可以提供帮助.非常感谢!

Hello All,

the below code in Timer code can not work in windows service. Anyone can help. Thanks a lot!

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Timers;

namespace WindowsService1
{
	public class Service1 : System.ServiceProcess.ServiceBase
	{
		private System.ComponentModel.Container components = null;
        public delegate void SaveDelegate (object source, ElapsedEventArgs e);
		private System.IO.StreamWriter file;
        public  Timer aTimer = new Timer(); 
		public Service1()
		{
			InitializeComponent();
		}
		// The main entry point for the process
		static void Main()
		{
			System.ServiceProcess.ServiceBase[] ServicesToRun;
	
			ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
			System.ServiceProcess.ServiceBase.Run(ServicesToRun);
			
		}
		private void InitializeComponent()
		{
			components = new System.ComponentModel.Container();
			this.ServiceName = "Service1";
			
            aTimer.Enabled = true;
            aTimer.Interval = 5000;
            aTimer.Elapsed += new ElapsedEventHandler(new SaveDelegate(saverecord));
		}
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		protected override void OnStart(string[] args)
		{
			
			file = new StreamWriter( new FileStream("ServiceTest.log", System.IO.FileMode.Append ) );
			this.file.WriteLine("Starting Service");
			this.file.Flush();
 		
            aTimer.Start();
			}
 
		protected override void OnStop()
		{
			this.file.WriteLine("Stopping Service");
			this.file.Close();
            aTimer.Stop();
		}
        private void saverecord(object source, ElapsedEventArgs e)
        {
          
            file = new StreamWriter(new FileStream("ServiceTest.log", System.IO.FileMode.Append));
            file.WriteLine("5 Saving Service");
            file.Flush();
        }
	}
}

推荐答案

首先,您应该解决OriginalGriff指出的问题.计时器开始工作后会引起问题.

我复制了您的代码以尝试重新创建问题并成功.计时器的编写方式永远不会触发.若要解决此问题,请从InitializeComponent方法中删除行aTimer.Enabled = true;.将Enabled设置为true会启动计时器,这对于服务的构造函数来说似乎是一件坏事(不要问我为什么).如果从OnStart启动计时器而不先从构造函数启动计时器,则一切似乎都正常.
First you should fix the problem that OriginalGriff pointed out. It will cause problems as soon as the timer starts working.

I duplicated your code to try to recreate the problem and succeeded. The way it''s written the Timer never fires. To fix the problem remove the line aTimer.Enabled = true; from the InitializeComponent method. Setting Enabled to true starts the timer which seems to be a bad thing to do from the constructor of the service (don''t ask me why). If you start the timer from OnStart without starting it first from the constructor everything seems to work OK.


我认为您的问题是:
1)启动计时器,然后在OnStart中打开日志文件.
2)您停止计时器并关闭OnStop中的日志文件.
3)作为计时器处理程序,您使用saverecord,它将覆盖现有的打开文件并尝试再次将其打开.
重新笔将失败,除非完成后关闭文件.

更好的方法是:
1)提供一个通用例程-说LogEvent(string eventDescription)
2)在OnStart中,启动计时器,使用LogEvent记录服务启动
3)在OnStop中,停止计时器,使用LogEvent记录服务停止
4)在saverecord中,使用LoEvent记录服务计时器事件.

LogEvent应该如下所示:
I think your problem is:
1) You start the timer and open the log file in OnStart.
2) You stop the timer and close the log file in OnStop.
3) As your timer handler, you use saverecord, which overwrites the existing open file with an attempt to open it again.
The re-pen will fail, unless you close the file when you have finished.

A better way to do it would be:
1) Provide a common routine - say LogEvent(string eventDescription)
2) in OnStart, start the timer, use LogEvent to log the service start
3) in OnStop, stop the timer, use LogEvent to log the service stop
4) in saverecord, use LoEvent to record the service timer event.

LogEvent should look like:
static void LogEvent(string eventDescription)
    {
    using (StreamWriter file = new StreamWriter(new FileStream("c:\\ServiceTest.log", System.IO.FileMode.Append)))
        {
        file.WriteLine(eventDescription);
        }
    }

这样,您就不会握住文件句柄,并在需要时打开文件.

This way you do not hold onto file handles, and your file is opened when you need it.


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

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