Question

Guilherme Bento Marques on Mon, 15 Oct 2012 18:54:34


Guys i'm trying to do a windows service that starts and 1 by 1 minute it writes a message in a text file.. But it doesn't work.. Here is my code. Can anyone help me?

public partial class Service1 : ServiceBase
    {
        //Inicializando o objeto timer
        Timer timer = new Timer();

        //Cria arquivo txt.
        StreamWriter vWriter = new StreamWriter(@"c:\testetimer.txt", true);

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // Chamando o Timer..
            //1: Adicionando o evento Elapsed ao objeto Timer
            timer.Elapsed += new ElapsedEventHandler(ContTimer);
            //2: Marcando o como intervalo 1 minuto (= 60,000 milliseconds)
            timer.Interval = 60000;
            //3: Habilitando o objeto timer para execução.
            timer.Enabled = true;
            timer.Start();
        }

        protected override void OnStop()
        {
            timer.Enabled = false; // Desabilita o timer.

            vWriter.WriteLine("Processo de envio de email parado: " + DateTime.Now.ToString());
            vWriter.Flush();
            vWriter.Close();
        }

        private void ContTimer(object source, ElapsedEventArgs e)
        {
            vWriter.WriteLine("Processo de envio de email iniciado: " + DateTime.Now.ToString());
            vWriter.Flush();
            vWriter.Close();
        }

    }


Sponsored



Replies

Chris Dunaway on Mon, 15 Oct 2012 20:05:04


The subject of your question indicates that you are getting an error.  What is the error you are getting?

Also, what kind of timer is it?  If it's System.Windows.Forms.Timer, then it will not work in a service.  You will need to use either System.Timers.Timer or System.Threading.Timer

Guilherme Bento Marques on Mon, 15 Oct 2012 20:21:24


There is no error.. sorry for the wrong subject.. But the looping doesn't work..

The loop shows me a message 60 seconds after starting the service.. And doesn't show it again..

I forgot to write that i'm using .. 

using System.Timers; // Classe de tempo.
using System.IO; // Classe de arquivos texto.

Could you help me please ?

Sri Velicheti on Mon, 15 Oct 2012 21:07:46


In your ContTimer method you are closing the streamwriter, once the streamwriter is closed you can nolonger access it.

Guilherme Bento Marques on Tue, 16 Oct 2012 11:50:50


Thanks Sri!! 

Sri Velicheti on Tue, 16 Oct 2012 15:57:47


Hi Guilherme Bento,

When you are hosting WCF Service in Windows Service it is always better to log all the errors in window event log, otherwise all the errors are lost.