views:

532

answers:

2

How can i perform various task (such as email alert/sending news letter) on a configured schedule time on a shared hosting server.

thankx dude , i love this website.

+6  A: 

Here's a Global.ascx.cs file I've used to do this sort of thing in the past, using cache expiry to trigger the scheduled task:

public class Global : HttpApplication
{
    private const string CACHE_ENTRY_KEY = "ServiceMimicCacheEntry";
    private const string CACHE_KEY = "ServiceMimicCache";

    private void Application_Start(object sender, EventArgs e)
    {
        Application[CACHE_KEY] = HttpContext.Current.Cache;
        RegisterCacheEntry();
    }

    private void RegisterCacheEntry()
    {
        Cache cache = (Cache)Application[CACHE_KEY];
        if (cache[CACHE_ENTRY_KEY] != null) return;
        cache.Add(CACHE_ENTRY_KEY, CACHE_ENTRY_KEY, null,
                  DateTime.MaxValue, TimeSpan.FromSeconds(120), CacheItemPriority.Normal,
                  new CacheItemRemovedCallback(CacheItemRemoved));
    }

    private void SpawnServiceActions()
    {
        ThreadStart threadStart = new ThreadStart(DoServiceActions);
        Thread thread = new Thread(threadStart);
        thread.Start();
    }

    private void DoServiceActions()
    {
        // do your scheduled stuff
    }

    private void CacheItemRemoved(string key, object value, CacheItemRemovedReason reason)
    {
        SpawnServiceActions();
        RegisterCacheEntry();
    }
}

At the moment, this fires off your actions every 2 minutes, but this is configurable in the code.

David M
+1 very nice, have done this sort of thing with session starts and common page loads before this seems much more suitable. Have you always found it to be reliable?
Robin Day
Question: What happens if the application fills up the cache (server runs low on memory), causing ASP.NET to prematurely clear out some of the Normal priority items - I think this would cause DoServiceActions to be executed more frequently then expected. Any ideas on how likely this is/work arounds?
David
I've not run into this issue, but it sounds like a plausible scenario. I guess a check on how recently the method was called using a stopwatch might be a workaround?
David M
A: 

Somone on here was doing this by creating threads in global.asax. Sounded like they were having success with it. I've never tested this approach myself.

This in my opinion would be a better option then overloading the cache expiration mechanism.

JoshBerke