how to use timer in foreach loop - c#

in a company I'm working we want to build an automation tool that should run a script written in text. I'm new to timers, and what I want to do is to make a foreach (not a must) that will run line after line in the script and call a parser for later use.
What I want is something like this:
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
foreach (ScriptCell CELL in ScriptList)
{
//fire the method when time is up
aTimer.Elapsed += new ElapsedEventHandler(DoScriptCommand(CELL.CellText));
}
I know what I wrote doesnt make allot of sense , but I'm a BIT clueless here
PS. I was looking in other topics before posting this Q , but I didnt find nothing that seems to fill the gap

The introduction of await makes acting on each item in a sequence, while waiting for a period of time between each item, very easy:
foreach(var cell in ScriptList)
{
DoScriptCommand(cell.CellText)
await Task.Delay(TimeSpan.FromSeconds(2));
}

Do this IN the elapsed event, not a new handler for each line (otherwise they'll be executed in a parallel manner)
aTimer.Elapsed += new ElapsedEventHandler((sender, args) =>
{
foreach (ScriptCell CELL in ScriptList)
{
DoScriptCommand(CELL.CellText);
}
}

If you are simply looking at running a script or scripts on a regular basis I would search "cron" if you are using a Unix/Linux machine or "Windows Task Scheduler" if you are using a windows machine. Each of these tools lets you specify a path to a script, the interval they should run, what command line parameters to use etc.

I did little tetris in my application.
I used timer for this code: I hope it will help you.
İf you dont use thread, your program will stuck while timer is running
so i used thread like this:
private void ciz()
{
int beklemeSuresi = 1000;//1000 = 1sec
for (int i = 0; i < 15; i++)
{
if (g != null)
{
g.Clear(Color.AliceBlue);
}
solLCiz(100, 100 + i * 20, yon);
Application.DoEvents();
Thread.Sleep(beklemeSuresi);
}
}
Of course you must begin thread at beginning of program like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ciz();
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

Related

How to make DispatcherTimer show time in a textbox and perform action when reaches a certain time in C#?

This is my second question on StackOverflow here. I posted my first question a while ago and got a working reply in no time, much impressed, much appreciated.
Anyways, so what I want to know is, how to get a DispatcherTimer to work and show time in a certain textbox and stop it when it reaches a certain time (let's say 60 seconds) and perform a function after 60 seconds.
What I'm basically using this for is :
Making a game, which has to stop after 60 seconds and show the scores or related stuff. So this requires me to show the time in a textbox and perform a function at 60 seconds or after that.
Here's more information :
Textbox is called "timerbox"
Here's the code I've tried :
DispatcherTimer dt = new DispatcherTimer();
private void TimerStart(object sender, RoutedEventArgs e)
{
dt.Interval = TimeSpan.FromSeconds(1);
dt.Tick += dt_Tick;
dt.Start();
}
int count = 0;
void dt_Tick(object sender, object e)
{
count = count + 1;
timerbox.Text = Convert.ToString(count);
}
It doesn't show the time in textbox, plus I don't know how to make it stop at certain point and perform a function.
Thank you for reaching here, please leave answers with full explanation as I'm a complete beginner :)
P.S. I'm using Windows Store App Development Environment in Visual Studio 2013.
And there's no "Timer" in it as there is in normal C# Environment.
AOA.
I am recently started learning c#. (interested in windows form application). Hope this help you.
if you just want to set timer for a curtain event.....
recommend you using timer ( in toolbox )......
follow steps, when you double click on timer1 VS will create a timer1_Tick function for you which will be called every timer you timer ticks.....
now what you want to do when timer1 icks write it in there....like this....
private void timer1_Tick(object sender, EventArgs e)
{
//enter your code here
}
now write timer1. and VS will display a list of avaliable function....
for example,
timer1.Interval = (60*1000); //enter time in milliseconds
now when you want to start the write......
timer1.Start();
and to stop timer at any timer call
timer1.Stop();
if you want to repeat timer just write timer1.start() in that tick function.....
plus, to set textbox text equal to timer1 time use something like
textBox1.Text = Convert.ToString(timer1.Interval);
Click here for more information on timer class
hope this help you,
in case of any confusion, just comment,.....
The normal flow of a DispatcherTimer would look like this:
First Set up your new Object, set up the a new EventHandler that will run your desired code each Tick and Set the Timespan for the desired Tick Interval.
public MainPage()
{
this.InitializeComponent();
timer = new DispatcherTimer();
timer.Tick += new EventHandler<object>(timer_Tick);
timer.Interval = TimeSpan.FromMilliseconds(bpm);
}
Set The Timer_Tick Envent
async Void timer_Tick(object Sender, object e)
{
await this.Dispatcher.RunAsync(Windows.UI.core.CoreDispatcherPriority.High, () =>
{
//Run the Code
textBox1.text = timer.interval.TotalMilliseconds.ToString();
});
You have to have a trigger to Start the Dispatcher(and to stop if you need to), for example a button
private void StartButton_Click()
{
timer.Start();
}
This example was done using The new windows 10 Universal App platform within VS2015, but I think it should look about the same in a normal windows 8 App

If the time is 1:00am Run the function in C#?

Is there a way in C# where if the time in PC or system says 1:00AM the function will run. I know this can be achieved using timer, but how can I do it? The code I am tinkering right now is this:
var t = new Timer { Enabled = true, Interval = 1 * 1000 };
t.Tick += delegate { mem_details(); };
But this code runs the function every 1 seconds, Do I need to compute 1:00AM to Seconds so I can do it using this code?
Please have a look to Quartz scheduler, I suppose it will help
http://quartz-scheduler.org/
Here is an example of how to configure Quartz for different time using cron strings:http://quartz-scheduler.org/documentation/quartz-2.2.x/examples/Example3.
You can use the online cron generator to select time you need.
You could always go with Microsoft's Reactive Framework to do this. The schedulers in there are incredibly robust.
You could write this code:
var start = DateTimeOffset.Now;
start = start.Date.AddHours(start.Hour == 0 ? 1.0 : 25.0);
/* start is now set for the next 1AM */
/* So schedule it */
Scheduler.Default.Schedule(start, reschedule =>
{
/* Do you thing as it's now 1AM */
/* And now reschedule to run tomorrow at 1AM */
reschedule(DateTimeOffset.Now.Date.AddHours(25.0));
});
Since you're using a 1 second timer why not check the time every tick?
EDIT:
Ok I changed my code a bit. It's still a 1 second timer (1000 milliseconds) but now when the timer tick event triggers, it only looks at the current hour and minute. Thus if your program is running a bit slow it will still run your process at 1 AM.
The global variable "lastRunDate" stores the date of when the last process run. This needs to be updated before your process runs just in case your process takes longer than a second to complete.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private String lastRunDate = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (lastRunDate != System.DateTime.Now.ToString("yyyy-MM-dd"))
{
String str = System.DateTime.Now.ToString("h:mm tt");
if (str.Equals("1:00 AM"))
{
lastRunDate = System.DateTime.Now.ToString("yyyy-MM-dd");
MessageBox.Show(str);
}
}
}
}
}
You can use timer and check time in it. For example
var t = new Timer { Enabled = true, Interval = 1 * 1000 };
t.Tick += delegate (object sender, EventArgs e)
{
if (DateTime.Now.TimeOfDay.TotalHours > 1 && DateTime.Now.TimeOfDay.TotalHours < 2)
{
mem_details();
(sender as Timer).Enabled=false;
}
};

create checkbox checking sequence

Hello I am trying to program some checkboxes to become checked and unchecked in a specific sequence programmatically. I know it sounds dumb, but this is corresponding to some LED controls that I've already coded the check events for.
I want to check a checkbox to start this sequence and uncheck it to stop it. Currently the checking and unchecking of my D2 checkbox occurs fine, but the do while loop freezes the form so I can't actually uncheck the cycle box. I probably should not be using Thread.Sleep either. Any advice is appreciated.
private void cycleCheckBox_CheckedChanged(object sender, EventArgs e)
{
do
{
D2.Checked = true;
Thread.Sleep(1000);
D2.Checked = false;
Thread.Sleep(1000);
} while (cycleCheckBox.Checked);
}
The Thread.Sleep method will run on the UI thread if called directly in the checked event which is why the UI is freezing. Push the work into a System.Windows.Forms.Timer (assumption is this is a WinForms app):
Implements a timer that raises an event at user-defined intervals.
This timer is optimized for use in Windows Forms applications and must
be used in a window.
Example based on your question:
Timer _timer;
private void cycleCheckBox_CheckedChanged(object sender, EventArgs e)
{
if(_timer == null )
{
_timer = new Timer();
_timer.Interval = 1000; // 1 second
_timer.Tick += DoTimerWork;
}
if(cycleCheckBox.Checked)
{
_timer.Start();
}
else
{
_timer.Stop();
}
}
private void DoTimerWork(object obj, EventArgs args)
{
D2.Checked = !D2.Checked;
}
I don't know if this will work for you but what I would do is drag in a Timer Control at 1000 ms and use a method to figure out which checkbox should currently be checked by using an integer that loops to 0 at a certain point and gets incremented at each tick.

How to add a timer to an app!

I have an app that I would like to update on an interval. I am looking for maybe some type of if statement or try - catch statement. I already have a foreach statement in the same class, but i dont think I can put in there? I would also like to set it up so that the user can change the refresh rate. Any help is appreciated. Thanks
Here is the method that I would like to put the timer in...
private void _UpdatePortStatus(string[] files)
{
foreach (string file in files)
{
PortStatus ps = new PortStatus();
ps.ReadXml(new StreamReader(file));
if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
{
_dicPortStatus.Add(ps.General[0].Group, ps);
}
PortStatus psOrig = _dicPortStatus[ps.General[0].Group];
foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
{
DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");
if (drs.Length == 1)
{
DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
DateTime newDt = psr.LastUpdateDateTimeUTC;
if (newDt > curDt)
{
drs[0]["LastUpdateDateTimeUTC"] = newDt;
}
}
else if (drs.Length == 0)
{
psOrig.Portstatus.ImportRow(psr);
}
else
{
throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
}
}
}
}
Look at the System.Timer class. You basically set an interval (eg. 10000 milliseconds) and it will raise an event every time that interval time passes.
To allow the use to change the refresh rate, write a method that receives input from the user and use that to update the TimerInterval. Note that the TimerInterval is in miliseconds, so you may need to convert to that from whatever the user input.
So, from the example, the event will be raised every 10 seconds:
System.Timers.Timer aTimer = new System.Timers.Timer(10000); //10 seconds
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true; // Starts the Timer
// Specify what you want to happen when the Elapsed event is raised
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Perform update
_UpdatePortStatus(files);
}
UPDATE: In response to your posted code, it appears you simply want to call _UpdatePortStatus to update the port status at regular intervals (see the updated example above).
One important point you need to bear in mind though is that the Timer will run on a separate thread, and as such could raise the event again before it has finished running from the last time if it takes more than the interval time to run.
Use System.Timers.Timer, System.Threading.Timer or System.Windows.Forms.Timer ... depending on what exactly it is that you "would like to update on an interval."
See the following articles:
http://www.intellitechture.com/System-Windows-Forms-Timer-vs-System-Threading-Timer-vs-System-Timers-Timer/
http://www.yoda.arachsys.com/csharp/threads/timers.shtml
Your question is somewhat vague as there an many different methods of achieving what you want to do. However in the simplest terms you need to create a System.Threading.Timer that ticks on whatever frequency you define, for example:
private System.Threading.Timer myTimer;
private void StartTimer()
{
myTimer = new System.Threading.Timer(TimerTick, null, 0, 5000);
}
private void TimerTick(object state)
{
Console.WriteLine("Tick");
}
In this example the timer will 'tick' every 5 seconds and perform whatever functionality you code into the TimerTick method. If the user wants to change the frequency then you would destroy the current timer and initialise with the new frequency.
All this said, I must stress that this is the simplest of implementation and may not suit your needs.

C# timer (slowing down a loop)

I would like to slow down a loop so that it loops every 5 seconds.
In ActionScript, I would use a timer and a timer complete event to do this. How would I go about it in C#?
You can add this call inside your loop:
System.Threading.Thread.Sleep(5000); // 5,000 ms
or preferable for better readability:
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
However, if your application has a user interface you should never sleep on the foreground thread (the thread that processes the applications message loop).
You can try using Timer,
using System;
public class PortChat
{
public static System.Timers.Timer _timer;
public static void Main()
{
_timer = new System.Timers.Timer();
_timer.Interval = 5000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true;
Console.ReadKey();
}
static void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//Do Your loop
}
}
Also if your operation in loop can last more then 5 sec, You can set
_timer.AutoReset = false;
to disable next timer tick until operation finish in loop
But then end end of loop You need again to enable timer like
_timer.Enabled = true;
Don't use a loop at all. Set up a Timer object and react to its fired event. Watch out, because these events will fire on a different thread (the timer's thread from the threadpool).
Let's say you have a for-loop that you want to use for writing to a database every second. I would then create a timer that is set to a 1000 ms interval and then use the timer the same way you would use a while-loop if you want it to act like a for-loop. By creating the integer before the loop and adding to it inside it.
public patial class Form1 : From
{
timer1.Start();
int i = 0;
int howeverLongYouWantTheLoopToLast = 10;
private void timer1_Tick(object sender, EventArgs e)
{
if (i < howeverLongYouWantTheLoopToLast)
{
writeQueryMethodThatIAssumeYouHave(APathMaybe, i); // <-- Just an example, write whatever you want to loop to do here.
i++;
}
else
{
timer1.Stop();
//Maybe add a little message here telling the user the write is done.
}
}
}

Categories