Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I have a windows service which should run every one hour, but its calling the function at the time of starting and after finishing the work only its says started and again after 1 hour it never call the function.

I put the code below, please suggest

C#
public PosNetService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            startservice();
        }


        private void startservice()
        {
            checkstatus();

        }

        private void checkstatus()
        {

            try
            {
                System.Threading.Thread.Sleep(1000 * 60 * 60);
// then remaining work to do
Posted

1 solution

With System.Timers.Timer you have more options, where System.Threading.Timer is a lightweight timer. I would recommend you to use System.Timers.Timer

Try this ...

C#
using System.Timers;

Timer tmrExecutor = new Timer();

protected override void OnStart(string[] args)
{
      tmrExecutor.Elapsed += new ElapsedEventHandler(tmrExecutor_Elapsed); // adding Event
      tmrExecutor.Interval = 5000; // Set your time here 
      tmrExecutor.Enabled = true;
      tmrExecutor.Start();
}

private void tmrExecutor_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
      //Do your work here 
}

protected override void OnStop()
{
      tmrExecutor.Enabled = false;
}
 
Share this answer
 
Comments
vaibhav mahajan 28-Sep-16 6:45am    
Worked for me. Thanks Sheikh Muhammad Haris.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900