I am having a problem get code to run through a system timer on a service , well actually no the timer IS firing , however the code below it will not run.
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Service Started");
//ad 1: handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
//ad 2: set interval to 1 minute (= 60,000 milliseconds)
timer.Interval = 60000;
timer.AutoReset = true;
//ad 3: enabling the timer
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
EventLog.WriteEntry("TIMER FIRED");
string[] filepaths = Directory.GetFiles(path, Filetype);
string result;
// Process Each String/File In Directory
foreach (string s in filepaths)
{
for (int i = 0; i < filepaths.Length; i++)
{
//Result Returns Video Name
result = Path.GetFileNameWithoutExtension(filepaths[i]);
PreformTranslation(filepaths[i], outputPath + result);
if (File.Exists(path + result))
{
MoveVideoFiles(path + result, outputPath + result);
}
}
}
}
So i See from the event viewer that it actually sends the "timer Fired" off each minute , but does not precede to run any of the code below. Without the timer in place the code runs as it should, so inititally i just tried calling the method, when that didn't work i just placed the code in the event handler hoping that would change. I think I've already lost when i resort to hope.
Related
I have console application am using as demo to an App, it prints "hello", based on the timespan its expected to alert the user. when its not yet the timespan, i want to delay the app from printing hello and resume when its time.
public static async void timeCounter(int delae)
{
//This is suppose to cause a delay but it instead initiate the
//TimerOperation_Tick method.
await Task.Delay(delae);
// timer countdown
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000; // 1 second
timer.Elapsed += new ElapsedEventHandler(TimerOperation_Tick);
timer.Start();
if (obj.SubmissionCheck == true)
{
timer.Stop();
}
}
/// the event subscriber
private static void TimerOperation_Tick(object e, ElapsedEventArgs args)
{
if (timeFrame != 0)
{
Console.WriteLine("hi" + timeFrame);
timeFrame --;
if (timeFrame < 1)
{
obj.SubmissionCheck = true;
nt.Remove(obj);
startNotification();
}
}
}
Try setting timer.Enabled = false; This will prevent the timer ticks from occurring.
My application is set to go to sleep when a notification balloontip is clicked and this process is all looped. This works, but when I awaken my computer, it goes to sleep shortly thereafter (this has a slight time delay, but as this takes as long as it normally takes for my computer to go to sleep, I wouldn't give this any consideration). I've removed this snippet from my overall program, and the program then works perfectly fine, making me think that there's something in this code that makes the computer go to sleep. Furthermore, in case one of the flags controlling the loops is reset, I've reset those flags, but the problem keeps happening. In case (for some strange reason) the boolean operators were impacting it, I've changed them in all the combinations I could, and it still didn't work! I've tried adding in a command to prevent the computer from going to sleep, but that didn't work either. Any suggestions? Much appreciated.
for (; ; )
{
bool for3 = false;
for (; ; )
{
notifyIcon.ShowBalloonTip(10000);
System.Threading.Thread.Sleep(10000);
Application.DoEvents();
if (loopVariable)
for3 = true;
if (for3) break;
System.Threading.Thread.Sleep(60000);
}
loopVariable = false;
for3 = false;
DateTime timeOnSleep = DateTime.Now;
Application.SetSuspendState(PowerState.Suspend, false, false);//this is the annoying code
DateTime timeOnWake = DateTime.Now;
TimeSpan time = timeOnWake - timeOnSleep;
var minutes = time.TotalMinutes;
Math.Round(time.TotalMinutes, MidpointRounding.AwayFromZero);
double dMins = minutes;
try
{
int iNumber = System.Convert.ToInt32(dMins);
}
catch (System.OverflowException)
{
if (dMins >= 40)
break;
}
}
private static bool loopVariable = false;
void notifyIcon_BalloonTipClicked(object sender, EventArgs e)
{
loopVariable = true;
}
If you find yourself using doevents, you're likely doing something wrong. If you needed to run a loop like that use do {} rather than for (;;). In any case, you don't need either of those things. If this isn't supposed to run infinitely, you can disable the timer just before calling Application.SetSuspendState.
void Main()
{
Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 30000; //How often you want to show the tooltip?
timer.Enabled = true;
}
void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{
Application.SetSuspendState(PowerState.Suspend, false, false);
}
void timer_Tick(object sender, EventArgs e)
{
notifyIcon1.ShowBalloonTip(10000);
}
I created a windows service, which will send mails to users based up on some conditions.
I had it installed on server in automatic mode. From the logs i can see that it ran successfully for first time and ended.
And i did not see it running again in the logs after that.
I checked the service in admin tools and it says it is started.
I also restarted service but no use, it did not start again.
Below is the code i used to start the service.
public partial class ScheduledService : ServiceBase
{
Timer timer;
private DateTime lastRun = DateTime.Now;
private DateTime DailyRunTime = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["DailyRunTime"]);
public ScheduledService()
{
InitializeComponent();
//GetDocRetentionList DocList = new GetDocRetentionList();
//DocList.GetDataSet();
}
protected override void OnStart(string[] args)
{
//System.Diagnostics.Debugger.Launch();
TraceService("start service");
//timer = new Timer(24 * 60 * 60 * 1000);
timer = new Timer(10 * 60 * 1000);
timer.Start();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
double TimerInterval = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["Timer"]);
timer.Interval = TimerInterval;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Service started at " + DateTime.Now);
if (lastRun.Date < DateTime.Now.Date)
{
if (DateTime.Now > DailyRunTime)
{
GetDocRetentionList DocList = new GetDocRetentionList();
DocList.GetDataSet();
timer.Stop();
lastRun = DateTime.Now.Date;
//timer.Start();
}
}
}
Any help i can get in this regard will be really helpful. Plz let me know.
Well.. your service is set to execute once, then it shuts the timer off in the OnElapsedTime method but never turns itself back on.
The first thing OnElapsedTime should do is turn off the timer. The last thing it should do is turn it back on.
Background: I have a timer that I am using to keep track of how long it has been since the serialPort DataReceived event has been fired. I am creating my own solution to this instead of using the built in timeout event because I am getting a continuous stream of data, instead of sending a query and getting one response.
The Problem:
In the DataReceived handler I have a statement to stop the timer so that is doesn't elapse. the problem is that a lot of the time it still executes the Elapsed handler afterword.
I have read that is is possible to use SynchronizingObject to solve this problem but I am not sure how to accomplish that.
Here is my code: I tried to cut out everything that I didn't think was relevant.
private System.Timers.Timer timeOut;
private System.Timers.Timer updateTimer;
public void start()
{
thread1 = new Thread(() => record());
thread1.Start();
}
public void requestStop()
{
this.stop = true;
this.WaitEventTest.Set();
}
private void record()
{
timeOut = new System.Timers.Timer(500); //** .5 Sec
updateTimer = new System.Timers.Timer(500); //** .5 Sec
timeOut.Elapsed += TimeOut_Elapsed;
updateTimer.Elapsed += updateTimer_Elapsed;
updateTimer.AutoReset = true;
comport.Open();
comport.DiscardInBuffer();
comport.Write(COMMAND_CONTINUOUSMODE + "\r");
stopwatch.Reset();
stopwatch.Start();
recordingStartTrigger(); //** Fire Recording Started Event
timeOut.Start();
updateTimer.Start();
this.waitHandleTest.WaitOne(); //** wait for test to end
timeOut.Stop();
updateTimer.Stop();
comport.Write(COMMAND_COMMANDMODE + Environment.NewLine);
comport.DiscardInBuffer();
comport.Close();
recordingStopTrigger(status); //** Fire Recording Stopped Event
stopwatch.Stop();
}
//***********************************************************************************
//** Events Handlers
private void comDataReceived_Handler(object sender, SerialDataReceivedEventArgs e)
{
double force = -100000;
string temp = "-100000";
//timeOut.SynchronizingObject.Invoke(new Action(()=> {timeOut.Stop();}), new object[] {sender, e});
timeOut.Stop();
//** I removed my action code here, keep things simple.
timeOut.Start();
}
private void TimeOut_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
timeOut.Stop();
updateTimer.Stop();
//** fire delegate that GUI will be listening to, to update graph.
if (eventComTimeOut != null && this.stop == false)
{
if (eventComTimeOut(this, new eventArgsComTimeOut(comport.PortName, "READ")))
{
//retry = true;
comport.Write(COMMAND_CONTINUOUSMODE + "\r");
updateTimer.Start();
timeOut.Start();
}
else
{
this.stop = true;
//retry = false;
this.WaitEventTest.Set();
status = eventArgsStopped.Status.failed;
}
}
}
void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//** fire delegate that GUI will be listening to, to update graph.
List<Reading> temp = new List<Reading>(report.Readings_Force);
eventNewData(this, new eventArgsNewData(temp));
}
This is well known behavior. System.Timers.Timer internally uses ThreadPool for execution. Runtime will queue the Timer in threadpool. It would have already queued before you have called Stop method. It will fire at the elapsed time.
To avoid this happening set Timer.AutoReset to false and start the timer back in the elapsed handler if you need one. Setting AutoReset false makes timer to fire only once, so in order to get timer fired on interval manually start timer again.
yourTimer.AutoReset = false;
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
// add your logic here
}
finally
{
yourTimer.Enabled = true;// or yourTimer.Start();
}
}
I did a pause in timer with this code. for me that works.
Private cTimer As New System.Timers.Timer
Private Sub inittimer()
cTimer.AutoReset = True
cTimer.Interval = 1000
AddHandler cTimer.Elapsed, AddressOf cTimerTick
cTimer.Enabled = True
End Sub
Private Sub cTimerTick()
If cTimer.AutoReset = True Then
'do your code if not paused by autoreset false
End If
End Sub
Had the same problem and after some trying ended up with timer object to null and replace the timer variable it with a new timer object fixed the issue. I know its heavy of resources. But it solves the problem.
I'm trying to create a Windows Form application that searches for a string and has three possible scenarios:
String 1 found - wait
String 2 found - stop
Else - Perform action and wait 1 minute
I am encountering my problem only on the times when it is expected to wait. When this happens, the newTimer_Tick starts to tick every second. I have tried disabling the timer when it ticks and a few other things but none appeared to work. Below is the code:
public void Action(string result)
{
if (result.Contains("string1"))
{
// Check again in 10 + x seconds
int n = new Random().Next(0, 5000);
int newtime = 10000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
else if (result.Contains("string2"))
{
// Turn off
newTimer.Enabled = false;
}
else
{
// Perform action and tick again in 1min + x seconds
action1();
int n = new Random().Next(0, 5000);
int newtime = 600000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
}
private void newTimer_Tick(object sender, EventArgs e)
{
Action( result );
}
What have I done wrong?
Each time the following line is called, an new instance of the event handler newTimerTick is added to the invocation list for the Tick event:
newTimer.Tick += new System.EventHandler(newTimer_Tick);
So every time the time tick goes off newTimerTick is going to be called multiple times, which is going to give you unexpected results.
Configure your event handler once only. In the constructor would be a sensible place.
Have you tried to stop the timer with the Timer.Stop method?
Btw: I don't think you need to reassign the Tick event from the newTimer unless you don't create a new Timer everytime.
I think what you were missing is that you have to stop your timer since you don't actually want it to keep for more than one interval. You seem to want to run it once, check on the result and then decide if you want to keep running it or not. Here's the code:
public void action(string result)
{
int n = new Random().Next(0, 5000);
Boolean blActivateTimer = true;
Timer timer = new Timer();
timer.Tick += timer_Tick;
if (!result.Contains("string1") && !result.Contains("string2"))
{
n += 600000;
action1();
}
else
{
if (result.Contains("string1"))
{
n += 10000;
}
else
{
blActivateTimer = false;
}
}
if (blActivateTimer)
{
timer.Start();
}
}
void action1()
{
}
void timer_Tick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
t.Stop();
action(result);
}