0

I have an ASP.NET (4.5+) app that calls an asynchronous task from Page_Load in order to obtain data for the page. I want to refresh that data every 15 minutes with out any user input.

First I tried using a timer and calling Page.ExecuteRegisteredAsyncTasks() in the timer function. No error but my async task never gets called. Just during Page_Load.

Then I tried various techniques for force a reload of the page figuring that would cause Page_Load to get called again but each attempt resulted in an exception being thrown saying that technique could not be used at that time.

The C# method I want to call every 15 minutes is defined as a private async Task.

What is the best way to call this method every 15 minutes? As I wrote above it is getting called successfully from Page_Load but never again.

Bob
  • 205
  • 2
  • 9
  • Related Question: [How to implement real time data for a web page](http://stackoverflow.com/questions/25829343/how-to-implement-real-time-data-for-a-web-page) – mason Dec 03 '15 at 19:54

2 Answers2

0

You will need to use a worker of some kind. If you had a timer then every time you refreshed the page, the timer would reset, you could use possibly a session variable to keep track. This is just the nature of the page lifecycle.

One alternative is to create a service, you could use an ASMX service for this and pull the data from the client-side. Using HTML5 Local Storage to keep track of the time last updated, or even "nextTimeToUpdate" store 15+ minutes from now. Set a time out of every 1 minute to check the current DateTime and if >= nextTimeToUpdate then trigger the request via AJAX.

Since local storage persists even after the browser is closed, when the user next visits the page and the data will still be there. The data is only lost if the user shuts down their machine/cleans their browser.

Edit

Assuming you want to trigger these events server-side. Move the async task into a new class, instantiate or inject it on the page you want.

Scott Hanselman has an article on How to run Background tasks in ASP.NET. A noteworthy library Hangfire

ZeroBased_IX
  • 2,667
  • 2
  • 25
  • 46
0

You have to use Timer, it is best way, I think.

Just follow next steps:

In design page:

<asp:ScriptManager ID="manager" runat="server" />
<asp:Timer ID="timer" runat="server" Interval="900000" OnTick="timer_Tick" />

Then create some function (e.g. MyFunc()), and your code behind:

protected void Page_Load(object sender, EventArgs e){
    MyFunc();
}
protected void timer_Tick(object sender, EventArgs e){
   MyFunc();
}
protected void MyFunc(){
   //do all actions, what you need, here
}
Khazratbek
  • 1,656
  • 2
  • 10
  • 17