Reputation: 2558
I am trying to initialize a timer that calls a method every second. I need to initialize it from within another event handler.
I wrote this code but it still gives me a compile error. They, both the initialization and the event handler are in the same class.
private void Controllel_Opened(object sender, EventArgs e)
{
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();
}
public static void DisplayTimeEvent(object source, ElapsedEventArgs e)
{
// code here will run every second
}
Any suggestions?
Upvotes: 2
Views: 2993
Reputation: 161
You can do the same from client side also.
[WebMethod]
public static void MyServerMethod()
{
//Code goes herer.
}
setInterval(function () {
$.post("../MyPage.aspx", function (data) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '../MyPage.aspx/MyServerMethod',
data: '{}',
async: false,
success: function (response) {
// code goes here.
});
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: -1
Reputation: 2558
Well, thanks, it made me look and I found that I simply was missing the reference before the ElapsedEventArgs
in the event handler.
So the code fully works as:
public static System.Timers.Timer myTimer = new System.Timers.Timer();
private void Controllel_Opened(object sender, EventArgs e)
{
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(DisplayTimeEvent);
myTimer.Interval = 1000; // 1000 ms is one second
myTimer.Start();
}
public static void DisplayTimeEvent(object source, System.Timers.ElapsedEventArgs e)
{
// code here will run every second
}
Thanks for looking.
Upvotes: 2