Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

scheduling - Scheduled jobs in ASP.NET website without buying dedicated servers

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...