none
How to schedule windows service in c#?

    Question

  •  

    Hi,

                I have created windows service in c#. I would like to schedule windows service manually or by coding .How can I do this.

    Actually, I am looking for

    My Service should start every day at 9’o clock in the morning and after some time My service should be stopped. As Microsoft has provided a Schedule Task in windows XP, where we can schedule any exe . In the same way how can I schedule any windows service to execute on specified time?

     

    Any help is appreciated

    Regards,

    Rajesh

    Wednesday, September 20, 2006 9:04 AM

All replies

  • You can use the net command:

    net start myservicename

    net stop myservicename

    Or, you can write your own by using the ServiceController class.

    Wednesday, September 20, 2006 9:12 AM
  • You need to write a service controller, just like SQL manager for SQL server. It'll be a system tray application with a Time checking time after some interval and Start and Stop the service accordingly at that time. for Controlling Service, FCL has class ServiceController. It provides several methods related to Service start, stop etc.

    You need to explore it yourself :P

    Cheers ;)

    Wednesday, September 20, 2006 9:01 PM
  • have a look at the following code

    namespace CLOSURE {
    public partial class Service1 : ServiceBase

    {

    #region MemberVariable

    private static FileStream fs = new FileStream(@"C:\ASR.txt", FileMode.OpenOrCreate, FileAccess.Write);

    private static StreamWriter m_streamWriter = new StreamWriter(fs);

    int j = 0;

    class1 sb = new class1 ();

    Timer timer;

    TimerCallback timercallback;

    #endregion

    #region Member Function

    #region CLOSURE Function

    private void Close_ASR(object sender)

    {

    DataTable dt = new DataTable();

    //Get all records where Station_Status=1

    dt = sb.GetStationDetails();

    string str = DateTime.Now.TimeOfDay.ToString().Substring(0, 5);

    m_streamWriter.WriteLine("{0} {1}", DateTime.Now.TimeOfDay.ToString().Substring(0, 5), " Executed.............");

    m_streamWriter.Flush();

    for (int i = 0; i < dt.Rows.Count; i++)

    {

    //To close the station ,When both the times are same

    if ((dt.Rows[i]["Time"].ToString() == DateTime.Now.TimeOfDay.ToString().Substring(0, 5))

    && Convert.ToInt32(dt.Rows[i]["CLOSURE_STATUS"].ToString()) == 1)

    {

    Closure obj = new Closure();

    m_streamWriter.WriteLine("{0} {1}", dt.Rows[i]["Station_Code"].ToString() + " " + "Closed", DateTime.Now.TimeOfDay.ToString().Substring(0, 5));

    m_streamWriter.Flush();

    dt.Rows[i]["closure_status"] = 1;

    sb.UpdateStationDetails(dt.Rows[i]["Station"].ToString());

    j = j + 1;

    }

    }

    if (j != dt.Rows.Count)

    {

    dt.Dispose();

    Close(new object());

    }

    else

    {

    j = 0;

    sb.ResetClosureStatus();

    }

    return;

    }

    #endregion

    #endregion

    #region Constructor

    public Service1()

    {

    InitializeComponent();

    sb.ResetClosureStatus();

    }

    #endregion

    #region Service Function

    protected override void OnStart(string[] args)

    {

    j = 0;

    timercallback = new TimerCallback(Close);

    timer = new Timer(timercallback, null, 0, 180000);

    Service1 obj = new Service1();

    }

    protected override void OnStop()

    {

    timer.Dispose();

    }

    #endregion

    }

    }

    in those above code in the constructor iam calling ResetClosureStatus() after that on the start of the service iam calling Close() in that for loop is running and loop will be running until it equals to row count once it got over i have to call the ResetClosureStatus() function and i have to call the
    Close() again it should run contiunously like 24 /7 please help its completing only one iteration i mean on the start which calls the Close() after that its not calling please help me


    ilikemicrosoft
    Wednesday, October 01, 2008 9:18 AM
  • could you please look at the code i posted in the forum
    ilikemicrosoft
    Friday, October 03, 2008 8:54 AM
  •   could you please look at the code i posted in the forum
    ilikemicrosoft
    Friday, October 03, 2008 8:54 AM
  • Why not use System.Timers.Timer?

    Timer timer = new Timer();
    timer.Enabled = true;
    timer.Interval = IntervalOfMinutes * Minute;
    timer.Elapsed +=
    new ElapsedEventHandler(Timer_Elapsed);

     
    protected override void OnStart(string[] args)
    {
       timer.AutoReset = true;
       timer.Enabled =
    true;
       timer.Start();
    }

    However, neither System.Timers.Timer or System.Threading.Timer solve the question asked. The question is how to schedule the service's task to run at a specific time of a day. The service itself should be able to be started at any time of the day.
    To be specific, if I want to schedule a task of a service to run at 3AM in the morning everyday, I don't want to be in office at 3 AM to start the service and let the timer to run every 24 hours. I want to install it, kick it off and it will be scheduled do the job at 3 AM.

    • Edited by Ethand Monday, August 17, 2009 11:42 PM
    Monday, August 17, 2009 10:29 PM
  • hi Ethand,
    did you find any solution for your quote mentioned above?
    I'm also in need of this kind of solution.

    for(;;)
    {
    if System.DateTime.now == some time
           startService();
    }

    This kind of logic will eat needless performance.
    do you have any better one?
    Vivek
    Tuesday, August 25, 2009 5:34 AM
  • Use system.timers.timer in this way


    timer = new System.Timers.Timer();
    timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    timer.AutoReset = true; // AutoReset = true means after specified interval the timer'll automatically be restarted
    timer.Interval = // specify some interval here in milliseconds e.g. 4 hours (4*60*60*1000)
    timer.Start();


    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                RunMyProcess();
            }
    • Proposed as answer by Ulhas Morbale Monday, March 19, 2012 10:04 AM
    Tuesday, August 25, 2009 7:13 AM
  • you can use this

    YourClass Cdata =new YourClass();

    DateTime

    nstart = DateTime.Now;
    DateTime nnow = DateTime.Now;
    TimeSpan ts = nstart - nnow;
    do
    {
    nnow =
    DateTime.Now;
    ts = nnow - nstart;
    // here you precise the time you need to wait to restart the service
    if (ts.Minutes >= 5)
    {
          nstart =
    DateTime.Now;
        
    string sprocessdate = DateTime.Today.ToShortDateString();

       // call you Method here
         Cdata.ExecService(sprocessdate);
    }
    }
    while (true);

    I hope this will help

    Wednesday, June 29, 2011 3:25 PM
  • Trigger tg = new DailyTrigger(); ScheduledTasks st = new ScheduledTasks(); Task t = st.OpenTask("foo"); t.Triggers.Add(tg); t.Save(); 
    

    Wednesday, November 02, 2011 2:09 PM
  • Either use a scheduled task (as others have mentioned), or set up a timer inside your service, which fires periodically (every 10 minutes for example) and check if the date changed since the last run:

    private Timer _timer; private DateTime _lastRun = DateTime.Now;  protected override void OnStart(string[] args) {     _timer = new Timer(10 * 60 * 1000); // every 10 minutes     
    
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);     //... 
    }   
    
    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    {     // ignore the time, just compare the date     
    if (_lastRun.Date < DateTime.Now.Date)     
    {        
     // stop the timer while we are running the cleanup task         _timer.Stop();         
    //         // do cleanup stuff         //         
    
    _lastRun = DateTime.Now;         _timer.Start();     
    } } 


     

    • Edited by Saurabh Suri Wednesday, November 02, 2011 2:13 PM
    Wednesday, November 02, 2011 2:11 PM