Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function every 5 minutes in background

Tags:

c#

asp.net

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?

like image 732
Paks Avatar asked Apr 16 '26 06:04

Paks


1 Answers

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); }
    }
}
like image 130
hackp0int Avatar answered Apr 18 '26 20:04

hackp0int