How to call function on timer ASP.NET MVC

I need to call function on timer (lets say onTickTack() function) and reload some info in ASP.NET MVC project. I know that there are several ways to do that, but which one is the best by your opinion?

Note: the function should be called from one place only, and should be called every X mins till application is up.

EDIT 1:
Reload some info – for example I have something in the Cache and I want to update it from DB on timer – once a day in certain time.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The answer to this question would very much depend on what do you mean by reload some info in ASP.NET MVC project. This is not a clearly stated problem and as such, more than obviously, it cannot have a clearly stated answer.

So if we assume that by this you want to periodically poll some controller action and update information on a view you could use the setInterval javascript function to periodically poll the server by sending an AJAX request and update the UI:

window.setInterval(function() {
    // Send an AJAX request every 5s to poll for changes and update the UI
    // example with jquery:
    $.get('/foo', function(result) {
        // TODO: use the results returned from your controller action
        // to update the UI
    });
}, 5000);

If on the other hand you mean executing some task on the server at regular periods you could use the RegisterWaitForSingleObject method like this:
var waitHandle = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
    waitHandle, 
    // Method to execute
    (state, timeout) => 
    {
        // TODO: implement the functionality you want to be executed
        // on every 5 seconds here
        // Important Remark: This method runs on a worker thread drawn 
        // from the thread pool which is also used to service requests
        // so make sure that this method returns as fast as possible or
        // you will be jeopardizing worker threads which could be catastrophic 
        // in a web application. Make sure you don't sleep here and if you were
        // to perform some I/O intensive operation make sure you use asynchronous
        // API and IO completion ports for increased scalability
    }, 
    // optional state object to pass to the method
    null, 
    // Execute the method after 5 seconds
    TimeSpan.FromSeconds(5), 
    // Set this to false to execute it repeatedly every 5 seconds
    false
);

If you mean something else, don’t hesitate to provide more details to your question.

Method 2

You can use the Timer class in OnApplicationStart Event of Glbal.asax…

public static System.Timers.Timer timer = new System.Timers.Timer(60000); // This will raise the event every one minute.
.
.
.

timer.Enabled = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
.
.
.

static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  // Do Your Stuff
}

Method 3

I do this by starting a worker thread from Application_Start().

Here’s my class:

public interface IWorker
{
    void DoWork(object anObject);
}

public enum WorkerState
{
    Starting = 0,
    Started,
    Stopping,
    Stopped,
    Faulted
}

public class Worker : IWorker
{
    public WorkerState State { get; set; }

    public virtual void DoWork(object anObject)
    {
        while (!_shouldStop)
        {
            // Do some work
            Thread.Sleep(5000);
        }

        // thread is stopping
        // Do some final work
    }

    public void RequestStop()
    {
        State = WorkerState.Stopping;
        _shouldStop = true;
    }
    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    protected volatile bool _shouldStop;
}

It’s started like this:
        var backgroundThread = new Thread(Worker.DoWork)
                                  {
                                      IsBackground = true,
                                      Name = "MyThread"
                                  };
        backgroundThread.Start();

Method 4

My solution is this way;

<script type="text/javascript">
    setInterval(
        function ()
        {
            $.post("@Url.Action("Method", "Home")", {}, function (data) {
                alert(data);
            });
        }, 5000)
</script>

Called Method;
[HttpPost]
public ActionResult Method()
{
  return Json("Tick");
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ebaad Uddin
Ebaad Uddin
2 months ago

is it harmful to my application in any sense if I use Method 2 Timer class to call a controller method Index() with regular intervals ?

2
0
Would love your thoughts, please comment.x
()
x