Saturday, February 19, 2011

What is the best way to implement background services for an ASP.NET application?

My ASP.NET application needs a number of supporting services to run periodically in the background. For example:

  • I need to query the database (or cache) every 1-5 minutes, identify overdue work items and notify users by email
  • I need to generate nightly reports that are then emailed to subscribers
  • Plus other system/non-user admin tasks

What is the best way to implement these services? Should I include them as part of the web application, starting an instance of each 'service' in Application_Start()? Or create them as actual standalone services? If they were part of the web application I can potentially utilize my cached data store, but are there any downsides to this approach?

Thanks for any advice.

From stackoverflow
  • -- For the nightly report generation I would look into SQL Reporting Services because they have some native subscription services that allow you to e-mail reports to users with virtual no custom code.

    -- For the overdue work item notifications you could either use SSRS (mentioned above) by sending them a report with their overdue items or, if you're running SQL 2k5, use Notification Services.

    gbjbaanb : if you're running SQL 2008, don't use Notification Services as they've removed it.
  • I do spinoff worker threads and threads that do things periodically in my ASP.NET application and I haven't had any problem.

    I don't just run the app in house - others download it and run it on their sites, or run it at hosting companies, so doing things without requiring that a service be installed makes the deployments easier.

  • This year I needed to implement a single task to cache some data from a database, It had to verify a changing code every n minutes, I found this very nice article;

    Simulate a Windows Service using ASP.NET to run scheduled jobs

    I did it that way and it worked, but as I told you was it was only a single task, but if you see the example above you can see that it performs several tasks.

    As you could see, in the cache you can perform a task at any time and on intervals, the nightly task could be done at midnight, the others every n minutes or hours.

    Hope it helps.

  • A timer combined with a background worker has worked well for me:

    Timer timer = new Timer(intervalSeconds * 1000)
    timer.Elapsed += delegate
    {
        // do the meat
    };
    timer.Start();
    

    Keep in mind that you won't have access to the HttpContext and that the site may shut down due to inactivity.

  • Honestly I've never been a fan of trying to simulate a windows service inside an ASP.net process, especially when you consider how easy it is to create a Windows service. Most of the attempts that I've seen at doing so have been full of problems.

0 comments:

Post a Comment