Quantcast
Channel: Visual C# forum
Viewing all articles
Browse latest Browse all 31927

Windows Service to run a function at specified time

$
0
0

I have created a windows service and i want it to call a function at specific time like say 7pm . How can i do that? Any help will be appreciated. 

The code is as follows

public partial class Shutdownservice : ServiceBase
    {

        Process p = new Process();
        System.Timers.Timer restartTimer;

        public Shutdownservice()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            restartTimer = new System.Timers.Timer();
            restartTimer.Elapsed += new System.Timers.ElapsedEventHandler(countForNoResponse);
            restartTimer.Interval = 30; // 
            restartTimer.Enabled = true;
            restartTimer.AutoReset = true;
            restartTimer.Start();
        }

        protected override void OnStop()
        {
        }
       
        public void countForNoResponse(object sender, System.Timers.ElapsedEventArgs args)
        {
            DateTime systemDate = DateTime.Now;
            DateTime compareDate = DateTime.Today.AddHours(15D);
            Process p = new Process();

            if (systemDate > compareDate)
            {
                int count = 0;
                while (count < 4)
                {
                    p.StartInfo = new ProcessStartInfo(@"C:\Windows\Temp\ShutdownSystem.exe");
                    p.Start();
                    bool wait = p.WaitForExit(1000 * 10);
                    if (!wait)
                    {
                        p.Kill();
                        System.Threading.Thread.Sleep(1000 * 10);
                        count++;
                        if (count == 4)
                        {
                            Process.Start("shutdown", "/s /t 900");
                        }
                    }
                    else
                    {
                        count = 6;
                    }
                }

                
            }
        }

    }
}

Thanks in advance :)


\m/


Viewing all articles
Browse latest Browse all 31927

Latest Images

Trending Articles



Latest Images