开发者

how to run a long running process in a windows service?

can someone let me know how to run a long running process from a windows service (in C#)? the process may take hours to finish. the service should check the database for any pending jobs to execute. each job can take any long to finish. if there are no pending jobs, then it should 开发者_如何转开发sleep for 2mins (configurable) and then start again. how can I do this using a windows service? Thanks in advance.


you have to create console apps something like this

    static void Main(string[] args)

    {
       bool createdNew;
        Mutex m = new Mutex(true, "YourBatchProcessor", out createdNew);
        if (!createdNew)
        {
             Console.WriteLine("YourBatchProcesso is already running!");
            return;
        }
        //your code goes here

    }

and as Gmoliv said create scheduled tasks than run every 2 minutes

or if you want to write window service then your service code like

   public class YourServrClass
   {

    private int numticks = 0;
    private Timer _timer;
    private bool _IsStarted;
    private int Interval =2000; //ticks //2 sec.
    #region Initializer
     public YourServrClass()
    {
        InitializeComponent();
        _timer = new Timer();
         _timer.Interval = Interval;
        _timer.Elapsed += new ElapsedEventHandler(this.Timer_Tick);
    }
    #endregion

    #region Timer_Tick to process

    private void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        numticks++;
        if (_IsStarted)
        {
            _timer.Stop();

            //your code //ProcessYourData();
            _timer.Start();
        }
    }
    #endregion
    protected override void OnStart(string[] args) 
    { 
           _IsStarted=true;
    } 

    protected override void OnStop() 
    { 
          _IsStarted=false;
    } 

 }


  1. Create a new "Windows Service" project.
  2. Override OnStart method to create either a thread. This thread will handle the polling and processing.
  3. Override the OnStop method to set a flag. The thread from step 2 watch for this flag and terminate itself accordingly.
  4. Open the design surface of the Service class. At the bottom of the Properties window is a link called "Add Installer". Click it.
  5. Install the suervice using InstallUtil or by putting it inside an installer package.

I write services all the time, so feel free to ask me follow-up questions.


There's no special trick to it, except you can't use any GUI/Forms or user input. A windows service by definition has no user I/O. Write errors to the event log and you're fine.


It is a lot easier to use windows scheduled tasks than develop your own app, you should give it a try.

If it doesn't work the way you expect, as Jay said, there's no trick, just remember there's no GUI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜