I can't get the timer to tick every time when i create a new command object I am wondering what is causing this. I am new to C# so if i could get help as to why this is happening it would be greatly appreciated.
This should trigger, but doesnt
command Cmd = new command("!example", 10);
Here's the code.
public class Timeout
{
public Timeout() { }
public static List<command> timeouts = new List<command>();
public class command
{
public string cmd;
public int seconds;
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 1000 };
public command(string cmd, int seconds)
{
Debug.WriteLine("created, " + cmd + ", " + seconds);
this.cmd = cmd;
this.seconds = seconds;
this.timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
Debug.WriteLine("tick -> " + seconds);
if (seconds > 0)
seconds--;
else
{
timer.Tick -= Timer_Tick;
timeouts.Remove(this);
Debug.WriteLine("removed");
}
}
}
}
actually you can do this way.
call the timer once you create the object
command cmd =new command("!example",10);
//then am calling the timer event
timer = new Timer(3000); // Set up the timer for 3 seconds
timer.Elapsed += new ElapsedEventHandler(timerElapsed);
//_timer_Elapsed is the event name
timer.Enabled = true;
public static void timerElapsed(object sender, ElapsedEventArgs e)
{
//do something here
}
please find the link here for more reference.hope my comment helps you :)
Related
I make a call via client side to initiate the StopTickerTimer function which successfully calls the StopTickerTimer function but unfortunately doesn't actually stop the timer. The timer starts and works properly but I can't seem to understand why my timer isn't stopping. I've tried setting timer.Enabled = false. I've tried various solutions that I've found on here but nothing seems to work.
public Timer timer = new Timer();
private string jsonContents;
private string currentTickerPlaylist;
private int i = 0;
private List<string> playlistTickers;
public void StartTickerTimer(int seconds, string selectedPlaylist)
{
currentTickerPlaylist = selectedPlaylist;
InitPlaylistTickerTimer(seconds);
}
public void StopTickerTimer()
{
StopTimer();
}
private void InitPlaylistTickerTimer(int seconds)
{
timer.Elapsed += new ElapsedEventHandler(t_Tick);
timer.Interval = seconds * 1000;
timer.AutoReset = true;
timer.Start();
}
private void StopTimer()
{
timer.Stop();
}
private void t_Tick(object sender, EventArgs e)
{
SetPlaylistTickerSettings();
if (i >= playlistTickers.Count)
{
i = 0;
Payload ticker = new Payload
{
ticker = playlistTickers[i]
};
Payload ticker2 = new Payload
{
payload = ticker
};
var json = ServiceStack.Text.JsonSerializer.SerializeToString(ticker2);
PutToSingular("url", json);
i++;
}
else
{
Payload ticker = new Payload
{
ticker = playlistTickers[i]
};
Payload ticker2 = new Payload
{
payload = ticker
};
var json = ServiceStack.Text.JsonSerializer.SerializeToString(ticker2);
PutToSingular("url", json);
i++;
}
}
You started your timer, but you are not calling your "StopTimer" anywhere in the code...
I'm writing Windows Service that calls for method after defined period of time (for now its 20 seconds). Everything was working fine until it didn't. Can't seem to find the cause of the problem.
Service seems to start and stop properly giving log entry, but it seems like it doesnt call for elapsed event.
public partial class UssPwdSyncService : ServiceBase
{
private Timer timer1 = null;
public UssPwdSyncService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
timer1 = new Timer();
this.timer1.Interval = 20000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_tick);
timer1.Enabled = true;
LogHandling.WriteErrorLogs("Service has started! LOg!");
}
catch (Exception ex)
{
LogHandling.WriteErrorLogs(ex);
}
}
private void timer1_tick(object sender, ElapsedEventArgs e)
{
ConfigurationManager.RefreshSection("connectionStrings");
foreach (ConnectionStringSettings cStr in ConfigurationManager.ConnectionStrings)
{
string name = cStr.Name;
string connString = cStr.ConnectionString;
string provider = cStr.ProviderName;
LogHandling.WriteErrorLogs(name + " " + connString + " " + provider);
}
LogHandling.WriteErrorLogs("This does something!");
}
protected override void OnStop()
{
timer1.Enabled = false;
LogHandling.WriteErrorLogs("Service has stoped!");
}
}
Could someone point out what am I missing?
I moved try catch to timer1_tick method.
This is the right place to exception check.
You can be throwing an exception o timer1_tick peace of code.
You have connectionStrings sections?
Note: i prefer to use Start and Stop methods instead of Enabled = true
and Enabled = false.
Two ways are right.
Try this:
public partial class UssPwdSyncService : ServiceBase
{
private Timer timer1 = null;
public UssPwdSyncService()
{
InitializeComponent();
this.timer1 = new Timer();
this.timer1.Interval = 20000;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_tick);
}
protected override void OnStart(string[] args)
{
this.timer1.Start();
LogHandling.WriteErrorLogs("Service has started! LOg!");
}
private void timer1_tick(object sender, ElapsedEventArgs e)
{
try
{
ConfigurationManager.RefreshSection("connectionStrings");
foreach (ConnectionStringSettings cStr in ConfigurationManager.ConnectionStrings)
{
string name = cStr.Name;
string connString = cStr.ConnectionString;
string provider = cStr.ProviderName;
LogHandling.WriteErrorLogs(name + " " + connString + " " + provider);
}
LogHandling.WriteErrorLogs("This does something!");
}
catch (Exception ex)
{
LogHandling.WriteErrorLogs(ex);
}
}
protected override void OnStop()
{
this.timer1.Stop();
LogHandling.WriteErrorLogs("Service has stoped!");
}
}
I assume you're using the Timer in System.Timers. You need to call the timer's Start() method.
i have problems with this timer, my function in the Tick event are appearing twice.. i want it to appear only once..
public void timerStart()
{
DispatcherTimer updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0,0,0,0,300);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
checkSigningAvailable();
updaterTimer.Start();
}
This is the method that is checked every tick of the timer,
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if (!InPopAlready)
{
InPopAlready = true;
disableSigningIn("False", this.event_id);
}
}
}
And the messagebox in the bottom is appearing twice after calling this function above
public void disableSigningIn(string Out,string event_id)
{
System.Console.WriteLine("POPED "+ InPopAlready);
connection.Open();
string sign = "True," + Out;
string query = "update data_storage set data_details = '" + sign + "' where data_name = 'Signing';";
NpgsqlCommand command = new NpgsqlCommand(query, connection);
command.ExecuteNonQuery();
connection.Close();
sign_in.Content = "Sign-in Time : Over";
string query2 = concatQuery(getIDnumberAttendance(event_id));
updateAbsences(query2);
MessageBox.Show("Signing in is over!", "No more signing in!", MessageBoxButton.OK, MessageBoxImage.Information);
}
You are adding " += new EventHandler " and adding and adding new EventHandlers all over new EventHandlers but never remove them..
All the previous one gets fired each Time the Timer Starts again.
You can reproduce this behaviour if you implement a counter, then you will see that is doubles with each new added and raised Event.
(Edit: Just was confused because the "new" keyword, but actually I will not delete the answer since I am pretty sure that in some cases it will exactly be the issue)
The following may help:
How to remove all event handlers from an event
And here the most easy solution:
(You may polish it by using delegates)
Declaration in Class:
private System.Windows.Threading.DispatcherTimer P5DispatcherHelpsystemTimer = new System.Windows.Threading.DispatcherTimer();
private EventHandler P5DispatcherTimerHandler;
Dispatcher Timer Method:
private void InitializeHelpsystemCronjobs(System.Windows.Controls.Canvas sub_CanvasElement)
{
P5DispatcherTimerHandler = (sender, e) => P5DispatcherHelpsystemTimerTick(sender, e, sub_CanvasElement);
P5DispatcherHelpsystemTimer.Tick += P5DispatcherTimerHandler;
P5DispatcherHelpsystemTimer.Interval = new TimeSpan(0, 0, 1);
P5DispatcherHelpsystemTimer.Start();
}
Dispatcher TimerTick Method:
private void P5DispatcherHelpsystemTimerTick(object sender, EventArgs e, System.Windows.Controls.Canvas sub_CanvasElement)
{
P5DispatcherHelpsystemTimer.Stop();
{
// Do stuff
}
P5DispatcherHelpsystemTimer.Start();
}
// Somewhere when an Trigger Event or Action etc. happens and the Timer shall start:
InitializeHelpsystemCronjobs(HelpsystemHelpCanvas);
// Somewhere when it sahll stop:
P5DispatcherHelpsystemTimer.Stop();
P5DispatcherHelpsystemTimer.Tick -= P5DispatcherTimerHandler;
(If you have more complex situation you definitely need delegate List<>)
For me, it was not starting, stopping or the Timer at all. It was the DI/IOC container resolving two instances of the ViewModel which started a new refresh timer in the constructor. Check to make sure that you are always seeing the same ViewModel instance and not actually two separate ones, firing two separate Timers.
The code below fires the MessageBox only once:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.timerStart();
}
DispatcherTimer updaterTimer;
private bool InPopAlready;
DateTime dt_signing_in;
public void timerStart()
{
updaterTimer = new DispatcherTimer();
updaterTimer.Tick += new EventHandler(updaterTimer_Tick);
updaterTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
updaterTimer.Start();
}
private void updaterTimer_Tick(object sender, EventArgs e)
{
updaterTimer.Stop();
checkSigningAvailable();
updaterTimer.Start();
}
public void checkSigningAvailable()
{
if (dt_signing_in.CompareTo(DateTime.Now) < 0)
{
if (!InPopAlready)
{
InPopAlready = true;
// Calling your method and showing MessageBox
MessageBox.Show("Signing in is over!", "No more signing in!", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}
I tend to write my "once-off" timer code like this:
var updaterTimer = new DispatcherTimer();
updaterTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
EventHandler tick = null;
tick = (s, e) =>
{
updaterTimer.Stop();
updaterTimer.Tick -= tick;
/* execute once-off code here */
};
updaterTimer.Tick += tick;
updaterTimer.Start();
Then I don't need to fluff with making new methods - it's all in one local code block.
i am working on a winform application in which i have a timer.it is being used for showing stopwatch on the form. When i fire a button than my timer is interrupted. i want my timer to be uninterrupted while button is clicked. My code is as followed:-
private void button1_Click(object sender, EventArgs e)
{
if (!_timerRunning)
{
// Set the start time to Now
_startTime = DateTime.Now;
// Store the total elapsed time so far
_totalElapsedTime = _currentElapsedTime;
_timer.Start();
_timerRunning = true;
}
SqlConnection Con = new SqlConnection("Data Source=69.162.83.242,1232;Initial Catalog=test1;Uid=test;pwd=1234#Test;MultipleActiveResultSets=true;Connect TimeOut=60000;");
//SqlConnection Con = new SqlConnection("Data Source=ADMIN-PC\\YASH;Initial Catalog=test;Integrated Security=True; Connect TimeOut=600");
Con.Open();
string messageMask = "{0} # {1} : {2}";
string message = string.Format(messageMask, label6.Text, DateTime.Now.ToShortTimeString(), richTextBox2.Text);
richTextBox1.AppendText(Environment.NewLine + message);
SqlCommand cmd, cmd1;
cmd = new SqlCommand("Update Chat set UserInitial=#message,Updated=1 where ExpertName ='" + label6.Text + "'", Con);
cmd.Parameters.AddWithValue("#message", message);
cmd.ExecuteNonQuery();
Con.Close();
richTextBox2.Text = String.Empty;
richTextBox1.ScrollToCaret();
}
private void timer1_Tick(object sender, EventArgs e)
{
richTextBox1.ScrollToCaret();
count = count + 1;
count1 = count1 + 1;
timerSinceStartTime = new TimeSpan(timerSinceStartTime.Hours, timerSinceStartTime.Minutes, timerSinceStartTime.Seconds + 1);
// The current elapsed time is the time since the start button was
// clicked, plus the total time elapsed since the last reset
_currentElapsedTime = timerSinceStartTime + _totalElapsedTime;
// These are just two Label controls which display the current
// elapsed time and total elapsed time
if (count1 == 180)
{
MessageBox.Show("You are Automaticlly hired by User");
if (label7.Visible == true)
{
label7.Visible = false;
count = 0;
timerSinceStartTime = new TimeSpan(00, 00, 00);
label3.Visible = true;
}
}
label3.Text = timerSinceStartTime.ToString();
// If we're running on the UI thread, we'll get here, and can safely update
// the label's text.
richTextBox1.ScrollToCaret();
}
how to solve it??
thanks in Advance
Your problem stems from the fact you're using System.Windows.Forms.Timer which is not threaded and relies on the message pump. While your program is busy in the UI thread the message pump won't be processed.
You can improve this by moving to a timer that supports threads. I prefer System.Timers.Timer but there's also System.Threading.Timer.
With System.Timers.Timer the tick event is raised on a background thread if you don't pass any sync object in so that any code within the event handler will be handled in a separate thread.
Of course, to update the form we have to marshal back to the UI thread so we'll also need to use Control.Invoke().
This is very rough, but something like this:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnTimer);
timer.Interval = 1000;
timer.AutoReset = false;
timer.Enabled = true;
public void OnTimer(object sender, ElapsedEventArgs e)
{
// Do something busy like dancing
// Update form
Invoke((MethodInvoker)delegate() {
UpdateForm();
});
// Restart timer
((System.Timers.Timer)sender).Start();
}
public void UpdateForm()
{
// Code to update the form
}
Note I use AutoReset = false so that if the tick event takes longer than the timer interval you won't get overlap. You may or may not want this it entirely depends on what you're doing.
You can try this,
private bool bStopTimer = true;
private void StartTimer()
{
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(this.ThreadTimer));
thread.IsBackground = true;
thread.Start();
}
private void ThreadTimer()
{
while (bStopTimer)
{
System.Threading.Thread.Sleep(1000); //interval in millisecond
lock(lblLabel.Text)
{
lblLable.Text = System.DateTime.Now.ToString("HH:mm:ss");
}
}
}
Update
place this line before Application.Run(new frmForm);
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
I'am trying to create watch folder aplicaction in C# that will do an action when new file will arrive. Since the watched folder is on GPFS share I'am unable to use FileSystemWatcher (which works fine for me in NTFS). So I've based the app on other collegue solution.
The app shows nicely "Timer starts" message but when it comes to
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
it did not calls the DoStuff method - "Starting new files proc" message never show up. What I've done wrong? Here is complete code:
namespace MonitorFolderActivity
{
public partial class frmMain : Form
{
List<string> fileList = new List<string>();
System.Timers.Timer timer;
DateTime LastChecked;
public frmMain()
{
InitializeComponent();
}
private void abortAcitivityMonitoring()
{
btnStart_Stop.Text = "Start";
txtActivity.Focus();
}
private void startActivityMonitoring(string sPath)
{
if (sPath.Length < 3)
{
MessageBox.Show("You have to enter a folder to monitor.",
"Hey..!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
abortAcitivityMonitoring();
}
else
{
TS_AddLogText(string.Format("Timer starts\r\n"));
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
}
private void stopActivityMonitoring()
{
TS_AddLogText(string.Format("Timer stops\r\n"));
this.timer.Stop();
}
private void DoStuff(object sender, System.Timers.ElapsedEventArgs e)
{
TS_AddLogText(string.Format("Starting new files proc\r\n"));
LastChecked = DateTime.Now;
string[] files = System.IO.Directory.GetFiles("D:\\MEDIAIN\\", "*", System.IO.SearchOption.AllDirectories);
foreach (string file in files)
{
if (!fileList.Contains(file))
{
fileList.Add(file);
TS_AddLogText(string.Format(file));
}
}
TimeSpan ts = DateTime.Now.Subtract(LastChecked);
TimeSpan MaxWaitTime = TimeSpan.FromMinutes(1);
if (MaxWaitTime.Subtract(ts).CompareTo(TimeSpan.Zero) > -1)
timer.Interval = MaxWaitTime.Subtract(ts).TotalMilliseconds;
else
timer.Interval = 1;
timer.Start();
}
private delegate void AddLogText(string text);
private void TS_AddLogText(string text)
{
if (this.InvokeRequired)
{
AddLogText del = new AddLogText(TS_AddLogText);
Invoke(del, text);
}
else
{
txtActivity.Text += text;
}
}
private void btnStart_Stop_Click(object sender, EventArgs e)
{
if (btnStart_Stop.Text.Equals("Start"))
{
btnStart_Stop.Text = "Stop";
startActivityMonitoring(txtFolderPath.Text);
}
else
{
btnStart_Stop.Text = "Start";
stopActivityMonitoring();
}
}
private void lblActivity_Click(object sender, EventArgs e)
{
}
private void lblToMonitor_Click(object sender, EventArgs e)
{
}
}
}
There are few issues in your code.
First of all you are not setting the time at which timer should elapse, which means it will read the default value which is
100 ms
Secondly you are not starting your timer. You need to add this line to your code in this method startActivityMonitoring else statement.
timer.Interval = yourdesiredinterval;
timer.Start();
Thirdly, as you are doing stop and start (by looks of your code) you should not create a new timer on each call of your startActivityMonitoring method. Rather you should do this
If(timer == null)
{
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Interval = yourinterval;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
}
timer.Start();
In your else clause, you never start the timer. Here's a fix:
else
{
TS_AddLogText(string.Format("Timer starts\r\n"));
timer = new System.Timers.Timer();
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(DoStuff);
timer.Start();
}