Results 1 to 3 of 3

Thread: [resolved] service with timer - timer event not firing

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2001
    Posts
    280

    [resolved] service with timer - timer event not firing

    hi,

    Ii wonder if anybody has any good experience when designing a service using c#.

    I need to perform some tasks on a server. its to regualry do some checking and other work and I dont really want a long running console app or it to be running in a user context, hence thought that writing it as a windows service was the way to go...

    I started checking out .net services with some testcode..

    I have done this many times before in std vb using the svrany tool from the NT-RK and have had little problem inthe past...

    at the moment I have got the following code before

    i'm installing it using the installutil.exe utility ("installutil <myservicenname>") and starting the service with "net start <myservicenname>".

    the service installs and starts ok - it logs a message in a file at start and stop time.

    what isn't happening is, I cannot seem to make the timer event fire and run my code! - i have copied my timer functionality to a standard .net form app and it works ok.

    I wonder if my design is wrong or am i missing some concept somewhere? etc.... at the begining the timer is loaded in the InitializeComponent() section and started in the OnStart() section.

    cannot understand why I done get a new file in my file evey secord (I havent got the file open in notepad or something silly like that)

    heres my code - any thoughts greatly appreciated

    cheers, AJP

    VB Code:
    1. using System;
    2. using System.Collections;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Diagnostics;
    6. using System.ServiceProcess;
    7. using System.IO;
    8. using System.Windows.Forms;
    9.  
    10. namespace WindowsService1
    11. {
    12.     public class Service1 : System.ServiceProcess.ServiceBase
    13.     {
    14.         private System.Windows.Forms.Timer timer1;
    15.         private System.ComponentModel.IContainer components;
    16.  
    17.         public Service1()
    18.         {
    19.             // This call is required by the Windows.Forms Component Designer.
    20.             InitializeComponent();
    21.  
    22.             // TODO: Add any initialization after the InitComponent call
    23.         }
    24.  
    25.         // The main entry point for the process
    26.         static void Main()
    27.         {
    28.             System.ServiceProcess.ServiceBase[] ServicesToRun;
    29.    
    30.             // More than one user Service may run within the same process. To add
    31.             // another service to this process, change the following line to
    32.             // create a second service object. For example,
    33.             //
    34.             //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
    35.             //
    36.             ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
    37.  
    38.             System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    39.         }
    40.  
    41.         /// <summary>
    42.         /// Required method for Designer support - do not modify
    43.         /// the contents of this method with the code editor.
    44.         /// </summary>
    45.         private void InitializeComponent()
    46.         {
    47.             this.components = new System.ComponentModel.Container();
    48.             this.timer1 = new System.Windows.Forms.Timer();
    49.             this.timer1.Tick += new EventHandler(Timer_Ticker);
    50.             this.ServiceName = "kgds_status_process";
    51.         }
    52.  
    53.         /// <summary>
    54.         /// Clean up any resources being used.
    55.         /// </summary>
    56.         protected override void Dispose( bool disposing )
    57.         {
    58.             if( disposing )
    59.             {
    60.                 if (components != null)
    61.                 {
    62.                     components.Dispose();
    63.                 }
    64.             }
    65.             base.Dispose( disposing );
    66.         }
    67.  
    68.         /// <summary>
    69.         /// Set things in motion so your service can do its work.
    70.         /// </summary>
    71.         protected override void OnStart(string[] args)
    72.         {
    73.             this.timer1.Interval = 1000;
    74.             this.timer1.Start();
    75.  
    76.             FileStream fs = new FileStream(@"c:\temp\status_process_log.txt" , FileMode.OpenOrCreate,    FileAccess.Write);
    77.             StreamWriter m_streamWriter = new StreamWriter(fs);
    78.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    79.             m_streamWriter.WriteLine("kgds_status_process: service started");
    80.             m_streamWriter.Flush();
    81.             m_streamWriter.Close();
    82.         }
    83.  
    84.         /// <summary>
    85.         /// Stop this service.
    86.         /// </summary>
    87.         protected override void OnStop()
    88.         {
    89.             FileStream fs = new FileStream(@"c:\temp\status_process_log.txt" , FileMode.OpenOrCreate, FileAccess.Write);
    90.             StreamWriter m_streamWriter = new StreamWriter(fs);
    91.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    92.             m_streamWriter.WriteLine("kgds_status_process: service stopped");
    93.             m_streamWriter.Flush();
    94.             m_streamWriter.Close();
    95.  
    96.             this.timer1.Stop();
    97.  
    98.         }
    99.  
    100.         private void Timer_Ticker (object sender, System.EventArgs e)
    101.         {
    102.             FileStream fs = new FileStream(@"c:\temp\status_process_log.txt" , FileMode.OpenOrCreate, FileAccess.Write);
    103.             StreamWriter m_streamWriter = new StreamWriter(fs);
    104.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    105.             m_streamWriter.WriteLine("tick - " + DateTime.Now.ToString());
    106.             m_streamWriter.Flush();
    107.             m_streamWriter.Close();
    108.         }
    109.  
    110.     }
    111. }
    Last edited by jpritchard; Nov 25th, 2005 at 05:21 AM.
    Intel 486dx3 - VB4 - DR-Dos - 2mb EdoRam - 2x CDrom drive - Window for Workgroups - CGA monitor

    Real programmers use less....

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: service with timer - timer event not firing

    The System.Windows.Forms.Timer class is intended for Windows Forms apps. Use the System.Timers.Timer class in a Service. I'm not 100% sure it will fix your issue but it is more correct. It is used in essentially the same way but it has an Elapsed event instead of Tick. Also, make sure you set the AutoReset property, which the WinForms version doesn't have, to True if you want the Elapsed event to be raised more than once.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Feb 2001
    Posts
    280

    Re: service with timer - timer event not firing

    hi jmcilhinney,

    your a star! thanks, got it working....

    actually I did read that the normally used timers was meant for forms

    anyhow - took on your comments and redid my code with the system.timers timer and got it sorted (I did previously did try this timer no luck (no event) - i think your comment about autoreset did the trick (i did know about this property) )

    thankyou for pointing me in the right direction, much appreciated
    cheers AJP

    working code below:-

    VB Code:
    1. using System;
    2. using System.Collections;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Diagnostics;
    6. using System.ServiceProcess;
    7. using System.IO;
    8. //using System.Windows.Forms;
    9. using System.Timers;
    10.  
    11. namespace WindowsService1
    12. {
    13.     public class Service1 : System.ServiceProcess.ServiceBase
    14.     {
    15.         private System.Timers.Timer proc_timer;
    16.         private System.ComponentModel.IContainer components;
    17.  
    18.         public Service1()
    19.         {
    20.             // This call is required by the Windows.Forms Component Designer.
    21.             InitializeComponent();
    22.  
    23.             // TODO: Add any initialization after the InitComponent call
    24.         }
    25.  
    26.         // The main entry point for the process
    27.         static void Main()
    28.         {
    29.             System.ServiceProcess.ServiceBase[] ServicesToRun;
    30.    
    31.             // More than one user Service may run within the same process. To add
    32.             // another service to this process, change the following line to
    33.             // create a second service object. For example,
    34.             //
    35.             //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
    36.             //
    37.             ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
    38.  
    39.             System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    40.         }
    41.  
    42.         /// <summary>
    43.         /// Required method for Designer support - do not modify
    44.         /// the contents of this method with the code editor.
    45.         /// </summary>
    46.         private void InitializeComponent()
    47.         {
    48.             this.components = new System.ComponentModel.Container();
    49. //          this.timer1 = new System.Windows.Forms.Timer();
    50. //          this.timer1.Tick += new EventHandler(Timer_Ticker);
    51.             this.proc_timer = new System.Timers.Timer();
    52.             this.proc_timer.Elapsed += new ElapsedEventHandler(proc_Timer_Ticker);
    53.             this.ServiceName = "gds_status_process";
    54.         }
    55.  
    56.         protected override void Dispose( bool disposing )
    57.         {
    58.             if( disposing )
    59.             {
    60.                 if (components != null)
    61.                 {
    62.                     components.Dispose();
    63.                 }
    64.             }
    65.             base.Dispose( disposing );
    66.         }
    67.  
    68.         protected override void OnStart(string[] args)
    69.         {
    70.             this.proc_timer.Interval = 1000;
    71.             this.proc_timer.AutoReset = true;
    72.             this.proc_timer.Start();
    73.  
    74.             FileStream fs = new FileStream(@"c:\temp\gds_status_process_log.txt" , FileMode.OpenOrCreate,    FileAccess.Write);
    75.             StreamWriter m_streamWriter = new StreamWriter(fs);
    76.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    77.             m_streamWriter.WriteLine("gds_status_process: service started");
    78.             m_streamWriter.Flush();
    79.             m_streamWriter.Close();
    80.         }
    81.  
    82.         protected override void OnStop()
    83.         {
    84.             FileStream fs = new FileStream(@"c:\temp\gds_status_process_log.txt" , FileMode.OpenOrCreate, FileAccess.Write);
    85.             StreamWriter m_streamWriter = new StreamWriter(fs);
    86.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    87.             m_streamWriter.WriteLine("gds_status_process: service stopped");
    88.             m_streamWriter.Flush();
    89.             m_streamWriter.Close();
    90.  
    91.             this.proc_timer.Stop();
    92.  
    93.         }
    94.  
    95.         private void proc_Timer_Ticker (object sender, System.Timers.ElapsedEventArgs e)
    96.         {
    97.             FileStream fs = new FileStream(@"c:\temp\gds_status_process_log.txt" , FileMode.OpenOrCreate, FileAccess.Write);
    98.             StreamWriter m_streamWriter = new StreamWriter(fs);
    99.             m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
    100.             m_streamWriter.WriteLine("tick - " + DateTime.Now.ToString());
    101.             m_streamWriter.Flush();
    102.             m_streamWriter.Close();
    103.         }
    104.     }
    105. }
    Intel 486dx3 - VB4 - DR-Dos - 2mb EdoRam - 2x CDrom drive - Window for Workgroups - CGA monitor

    Real programmers use less....

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width