Paks
Paks

Reputation: 1470

Execute function every 5 minutes in background

I have function which reads Data out of an Webservice. With that Data i create Bitmaps. I send the Bitmaps to Panels (Displays) which displays the created Bitmaps. Manually its working like charm. What i need now is, that my Application run this function every 5 min automtically in the Backround.

My Application is running under IIS. How can i do that? Can someone help me with that?

Upvotes: 3

Views: 4266

Answers (2)

hackp0int
hackp0int

Reputation: 4161

You don't have to be depended on asp.net project, but you can use Cache Callback to do it. I have found a nice approach, to do it. actually i don't remember the link so i'll give you a code that i use:

public abstract class Job
{
    protected Job()
    {
        Run();
    }

    protected abstract void Execute();
    protected abstract TimeSpan Interval { get; }

    private void Callback(string key, object value, CacheItemRemovedReason reason)
    {
        if (reason == CacheItemRemovedReason.Expired)
        {
            Execute();
            Run();
        }
    }

    protected void Run()
    {
        HttpRuntime.Cache.Add(GetType().ToString(), this, null, 
            Cache.NoAbsoluteExpiration, Interval, CacheItemPriority.Normal, Callback);
    }
}

Here is the implementation
public class EmailJob : Job
{
    protected override void Execute()
    {
        // TODO: send email to whole users that are registered 
    }

    protected override TimeSpan Interval
    {
        get { return new TimeSpan(0, 10, 0); }
    }
}

Upvotes: 3

Blachshma
Blachshma

Reputation: 17385

An Asp.Net application is not the correct framework for a task like this.

You should probably create a dedicated service for this type of tasks.

Another option is to create a scheduled task that will run every X minutes

On a side note, if you must do this through your asp.net application, I recommend reading on how to Simulate a Windows Service using ASP.NET to run scheduled jobs

Upvotes: 3

Related Questions