i have this timer in c#:
public class HomeController : Controller
{
public int count = 0;
public ActionResult Index()
{
Timer timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += new ElapsedEventHandler(onTimer);
timer.Start();
return View();
}
public void onTimer(Object source, ElapsedEventArgs e)
{
count++;
}
[HttpPost]
public JsonResult CheckStatus()
{
return Json(count);
}
and this is my view:
<script type="text/javascript">
$(function () {
// poll every 5 seconds
setInterval('checkStatus()', 3000);
});
function checkStatus() {
$.ajax({
url: 'Home/CheckStatus',
type: 'POST',
dataType: 'json',
success: function (xhr_data) {
document.getElementById("test").innerText = xhr_data;
}
});
}
Why does it keep show me (when running) only 0 ? why doesn’t it show me: 0,1,2 etc.. ?
A new instance of the controller will be created each time you make a request. Thus your repeated AJAX calls just get 0, since that’s what the
countvalue is initialized to.There will likely be other controllers (with timers running) floating around until the GC runs to collect them, but they will have no effect on the new controller that is actually processing each individual request.
I don’t know what problem you’re trying to solve with this code, but have you investigated the
setTimeoutandsetIntervaljavascript methods? They provide client-side timer services, and might be well-suited for your task.If you need persistent server-side data, then there are number of options, including:
Which, if any, are right for you depends on the actual problem you’re trying to solve.