I have a Windows Forms application written in C#. The following function checks whenever printer is online or not:
public void isonline()
{
PrinterSettings settings = new PrinterSettings();
if (CheckPrinter(settings.PrinterName) == "offline")
{
pictureBox1.Image = pictureBox1.ErrorImage;
}
}
and updates the image if the printer is offline. Now, how can I execute this function isonline() every 2 seconds so when I unplug the printer, the image displayed on the form (pictureBox1) turns into another one without relaunching the application or doing a manual check? (eg. by pressing "Refresh" button which runs the isonline() function)
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer() in Form1_Load().
.NET 6 has added the PeriodicTimer class.
var periodicTimer= new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await periodicTimer.WaitForNextTickAsync())
{
// Place function in here..
Console.WriteLine("Printing");
}
You can run it in the background with this:
async Task RunInBackground(TimeSpan timeSpan, Action action)
{
var periodicTimer = new PeriodicTimer(timeSpan);
while (await periodicTimer.WaitForNextTickAsync())
{
action();
}
}
RunInBackground(TimeSpan.FromSeconds(1), () => Console.WriteLine("Printing"));
The main advantage PeriodicTimer has over a Timer.Delay loop is best observed when executing a slow task.
using System.Diagnostics;
var stopwatch = Stopwatch.StartNew();
// Uncomment to run this section
//while (true)
//{
// await Task.Delay(1000);
// Console.WriteLine($"Delay Time: {stopwatch.ElapsedMilliseconds}");
// await SomeLongTask();
//}
//Delay Time: 1007
//Delay Time: 2535
//Delay Time: 4062
//Delay Time: 5584
//Delay Time: 7104
var periodicTimer = new PeriodicTimer(TimeSpan.FromMilliseconds(1000));
while (await periodicTimer.WaitForNextTickAsync())
{
Console.WriteLine($"Periodic Time: {stopwatch.ElapsedMilliseconds}");
await SomeLongTask();
}
//Periodic Time: 1016
//Periodic Time: 2027
//Periodic Time: 3002
//Periodic Time: 4009
//Periodic Time: 5018
async Task SomeLongTask()
{
await Task.Delay(500);
}
PeriodicTimer will attempt to invoke every n * delay seconds, whereas Timer.Delay will invoke every n * (delay + time for method to run) seconds, causing execution time to gradually move out of sync.
The most beginner-friendly solution is:
Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:
private void wait_Tick(object sender, EventArgs e)
{
refreshText(); // Add the method you want to call here.
}
No need to worry about pasting it into the wrong code block or something like that.
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
Things have changed a lot with time.
You can use the solution below:
static void Main(string[] args)
{
var timer = new Timer(Callback, null, 0, 2000);
//Dispose the timer
timer.Dispose();
}
static void Callback(object? state)
{
//Your code here.
}
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
using System;
using System.Timers;
namespace SnirElgabsi
{
class Program
{
private static Timer timer1;
static void Main(string[] args)
{
timer1 = new Timer(); //new Timer(1000);
timer1.Elpased += (sender,e) =>
{
MyFoo();
}
timer1.Interval = 1000;//miliseconds
timer1.Start();
Console.WriteLine("press any key to stop");
Console.ReadKey();
}
private static void MyFoo()
{
Console.WriteLine(string.Format("{0}", DateTime.Now));
}
}
}
Related
I have seen plenty of examples (here and elsewhere) of creating a non-reentrant timer by stopping the timer when the elapsed handler method is called and starting it again at the end of the elapsed handler method. This seems to be the recommended approach. The problem with this approach is that you will have a gap in time while the Elapsed Handler Method is running. You could end up with timing that is off by quite a lot within a short period of time.
So I was thinking about a better approach and I can up with the idea to use a bool to determine the state of the Timer, and whether the Elapsed Handler is currently running or not, it is is running then the call to the Elapsed Handler is returned immediately and the rest is not executed.
Below is the basic Idea
volatile bool _IsProcessingElapsedMethod = false;
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_IsProcessingElapsedMethod)
{
Console.WriteLine("Warning: Re-Entrance was attempted and Ignored.");
return;
}
_IsProcessingElapsedMethod = true;
//** DO Something here
_IsProcessingElapsedMethod = false;
}
There has to be a reason I have never seen anyone do this. Am I missing some obvious Gotcha? It seems like a pretty easy solution.
Below is a compilable example.
using System;
using System.Threading.Tasks;
using System.Timers;
namespace QuestionNon_ReEntrantTimer
{
class Program
{
static private int Timer1_ElapsedCount = 1;
static void Main(string[] args)
{
NonReEntrantTimer timer1 = new NonReEntrantTimer(500);
timer1.Elapsed += Timer1_Elapsed;
timer1.Start();
Console.WriteLine("Press Any key to Exit");
Console.ReadKey();
}
private static void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
int delayTime;
if(Timer1_ElapsedCount < 10)
{
delayTime = 300 * Timer1_ElapsedCount++;
}
else
{
Timer1_ElapsedCount++;
delayTime = 400;
}
Console.WriteLine($"Timer1_Elapsed Call Count is {Timer1_ElapsedCount} Waiting for {delayTime} ms");
Task.Delay(delayTime).Wait();
}
}
public class NonReEntrantTimer : IDisposable
{
Timer _timer = new Timer();
public event ElapsedEventHandler Elapsed;
volatile bool _IsProcessingElapsedMethod = false;
public NonReEntrantTimer(double interval)
{
_timer = new Timer(interval);
_timer.Elapsed += _timer_Elapsed;
}
public void Start() => _timer.Start();
public void Stop() => _timer.Stop();
public void Close() => _timer.Close();
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_IsProcessingElapsedMethod)
{
Console.WriteLine("Warning: Re-Entrance was attempted and Ignored.");
return;
}
_IsProcessingElapsedMethod = true;
Elapsed?.Invoke(sender, e);
_IsProcessingElapsedMethod = false;
}
public void Dispose()
{
_timer.Dispose();
}
}
}
I would propose this simple async pattern. It executes the given Action every ts, but starts countdown to the next execution before starting the current iteration. If the execution takes more time than ts, the next iteration is postponed till after the previous one finishes.
async Task ExecuteEvery(TimeSpan ts, Action a, CancellationToken ct)
{
try
{
var currentDelay = Task.Delay(ts, ct);
while (!ct.IsCancellationRequested)
{
await currentDelay; // waiting for the timeout
currentDelay = Task.Delay(ts, ct); // timeout finished, starting next wait
a(); // executing action in the meanwhile
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// if we are cancelled, nothing to do, just exit
}
}
You can stop the iterations by cancelling the token. You can offload the action execution to the thread pool by starting the operation with Task.Run.
Update: if you want the timer to try catching up after the slow action, you can do it with some minor changes:
async Task ExecuteEvery(TimeSpan ts, Action a, CancellationToken ct)
{
try
{
for (var targetTime = DateTime.Now + ts; !ct.IsCancellationRequested; targetTime += ts)
{
var timeToWait = targetTime - DateTime.Now;
if (timeToWait > TimeSpan.Zero)
await Task.Delay(timeToWait, ct);
a();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// if we are cancelled, nothing to do, just exit
}
}
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.
I have an application that I need to have wait a specific amount of time, but I also need to be able to cancel the current operation if needed. I have the following code:
private void waitTimer(int days)
{
TimeSpan waitTime = TimeSpan.FromDays(days);
System.Timers.Timer timer = new System.Timers.Timer(waitTime.TotalMilliseconds); // Wait for some number of milliseconds
timer.Enabled = true;
timer.Start();
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Subscribe to event handler
while (!TimerSettings.TimerFinished && !quitToken.IsCancellationRequested); // Loop forever untill timer is finished or operation is cancled.
timer.Elapsed -= new ElapsedEventHandler(OnTimedEvent); // Unsubscribe
DoWork(); // Do work when timer finishes.......
}
Below is the event handler for the timer finished event:
private void OnTimedEvent(object obj, ElapsedEventArgs e)
{
TimerSettings.TimerFinished = true;
}
The while loop just loops infinitely until the timer is finished or until a cancelation request is put in. I want to retain this functionality but I would rather not loop forever while waiting for the timer to finish. My timer can be set to run on an interval of multiple days so it doesn't make sense to loop for so long.
Is there another way of doing this?
I know I could do:
Thread.Sleep(runDuration.TotalMilliseconds);
However, this would be blocking and I would not be able to put in a cancelation request.
EDIT: So in order to elaborate on what/why I need to pause here is a more detailed explination of my application. Basically I want to have an application that performs "work" on a regular interval. So based on one of the answers provided below, if I did something like this:
class Program
{
// Do something in this method forever on a regular interval
//(could be every 5min or maybe every 5days, it's up to the user)
static void Main(string[] args)
{
while(true)
{
if(args?.Length > 0)
waitTimer(args[0]);
else
wiatTimer(TimeSpan.FromDays(1).TotalSeconds); // Default to one day interval
}
}
private void waitTimer(int numIntervals)
{
this.ElapsedIntervals = 0;
this.IntervalsRequired = numIntervals;
this.timer = new System.Timers.Timer(1000); // raise the elapsed event every second
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Subscribe to event handler
//timer.Enabled = true; timer.Start() does this for you, don't do this
timer.Start();
//thats all here
}
private void OnTimedEvent(object obj, ElapsedEventArgs e)
{
this.ElapsedIntervals += 1;
if(this.CancelRequested)
{
this.ElapsedIntervals = 0;
this.timer.Stop();
return;
}
if(this.ElapsedIntervals >= this.IntervalsRequired)
{
this.ElapsedIntervals = 0;
this.timer.Stop();
DoWork(); // This is where my work gets done.......
return;
}
}
}
Then my service/console app would start and go into an infinite loop that just sets timers all day long. Previously, I was actually halting execution of any other code at:
while (!TimerSettings.TimerFinished && !quitToken.IsCancellationRequested);
Which at least worked, but as mentioned, can possibly be resource intensive way to pause a thread. Basically what I really need is a way to block my thread untill the timer is up.
EDIT2: This is my final implementation that seems to work for me using a wait handle...
class TimerClass
{
/// <summary>
/// Initialize new timer. To set timer duration,
/// either set the "IntervalMinutes" app config
/// parameter, or pass in the duration timespan.
/// </summary>
/// <param name="time"></param>
internal bool StartTimer(CancellationToken quitToken, TimeSpan? duration = null)
{
TimeSpan runDuration = new TimeSpan();
runDuration = duration == null ? GetTimerSpan() : default(TimeSpan);
if (runDuration != default(TimeSpan))
{
WaitTimer(runDuration); // Waits for the runduration to pass
}
return true;
}
/// <summary>
/// Get duration to run the timer for.
/// </summary>
internal TimeSpan GetTimerSpan()
{
TimerSettings.Mode = App.Settings.Mode;
DateTime scheduledTime = new DateTime();
switch (TimerSettings.Mode)
{
case "Daily":
scheduledTime = DateTime.ParseExact(App.Settings.ScheduledTime, "HH:mm:ss", CultureInfo.InvariantCulture);
if (scheduledTime > DateTime.Now)
TimerSettings.TimerInterval = scheduledTime - DateTime.Now;
else
TimerSettings.TimerInterval = (scheduledTime + TimeSpan.FromDays(1)) - DateTime.Now;
break;
case "Interval":
double IntervalMin = double.TryParse(App.Settings.PollingIntervalMinutes, out IntervalMin) ? IntervalMin : 15.00;
int IntervalSec = Convert.ToInt32(Math.Round(60 * IntervalMin));
TimeSpan RunInterval = new TimeSpan(0, 0, IntervalSec);
TimerSettings.TimerInterval = RunInterval;
break;
case "Manual":
TimerSettings.TimerInterval = TimeSpan.FromMilliseconds(0);
break;
default:
TimerSettings.TimerInterval = (DateTime.Today + TimeSpan.FromDays(1)) - DateTime.Now;
break;
}
return TimerSettings.TimerInterval;
}
/// <summary>
/// Event handler for each timer tick.
/// </summary>
/// <param name="obj"></param>
/// <param name="e"></param>
private void OnTimedEvent(object obj, ElapsedEventArgs e)
{
ElapsedIntervals += 1;
if (CancelRequested.IsCancellationRequested) // If the application was cancled
{
ElapsedIntervals = 0;
timer.Stop();
WaitHandle.Set();
return;
}
if (ElapsedIntervals >= IntervalsRequired) // If time is up
{
ElapsedIntervals = 0;
timer.Stop();
WaitHandle.Set();
return;
}
}
/// <summary>
/// Timer method to wait for a
/// specified duration to pass.
/// </summary>
/// <param name="span"></param>
private void WaitTimer(TimeSpan span)
{
WaitHandle = new AutoResetEvent(false);
int tickDuration = 1000; // Number of milliseconds for each tick
IntervalsRequired = Convert.ToInt64(span.TotalMilliseconds / (tickDuration > 0 ? tickDuration : 0.01));
timer = new System.Timers.Timer(tickDuration); // Raise the elapsed event every tick
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Subscribe to event handler for when each tick is complete
timer.Start(); // Start ticking
WaitHandle.WaitOne(); // Halt the main thread untill span is reached
}
// Timer parameters:
private static long ElapsedIntervals { get; set; }
private static long IntervalsRequired { get; set; }
private static System.Timers.Timer timer { get; set; }
private static CancellationToken CancelRequested { get; set; }
private static string Mode { get; set; }
private static TimeSpan TimerInterval { get; set; }
private static EventWaitHandle WaitHandle { get; set; }
}
internal static class TimerSettings
{
internal static string Mode { get; set; }
internal static TimeSpan TimerInterval { get; set; }
}
You should look at the Timer.Elapsed Event documentation. This event will be raised repeatedly every time the interval elapses while the AutoReset property is set to true (which is default). I would keep your own count of how many intervals have elapsed and compare it to the required elapsed intervals in this event handler to check whether it is time to stop the timer. In that event, you can also handle cancellation. If your timer finishes its required number of intervals, you may call your doWork function from that event handler.
private void waitTimer(int numIntervals)
{
this.ElapsedIntervals = 0;
this.IntervalsRequired = numIntervals;
this.timer = new System.Timers.Timer(1000); // raise the elapsed event every second
timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Subscribe to event handler
//timer.Enabled = true; timer.Start() does this for you, don't do this
timer.Start();
//thats all here
}
private void OnTimedEvent(object obj, ElapsedEventArgs e)
{
this.ElapsedIntervals += 1;
if(this.CancelRequested)
{
this.ElapsedIntervals = 0;
this.timer.Stop();
return;
}
if(this.ElapsedIntervals >= this.IntervalsRequired)
{
this.ElapsedIntervals = 0;
this.timer.Stop();
DoWork();
return;
}
}
https://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx
As I see it, with regards to "pausing", there are two reasons to want to pause and I am unsure which reason is yours:
You want to prevent the application from "finishing" execution and terminating normally.
You want to hold off on executing other code until the number of required intervals has elapsed
If your reason is #2, then this answer is complete.
First of all: "you absolutely do not(!) want to 'busy-wait' for anything!" (BAD Dog! NO Biscuit!)
Ahem...
A practical solution to this problem is to perform a timed wait on a semaphore (or any other suitable mutual-exclusion object ...), instead of using an actual Timer. If you need to bust-out of the wait before it is finished, just strobe the thing upon which it is waiting.
The critical problem with your present "solution" is that it will slam the process into 100% CPU utilization, altogether wastefully. Never do that!
I'm having issues creating a timer that when started will first sleep for 2 minutes. It will run for 5 minutes total and every minute will do work. This is what I have:
class Program{
static System.Timers.Timer aTimer;
static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
static TimeSpan LongToRun = new TimeSpan(0,300,0)); //run for 5 minutes
static void Main (string[] args){
Thread.Sleep(120000); //sleep for 2 mins
sw.Reset();
sw.Start();
Start();
}
static void Start()
{
aTimer = new System.Timers.Timer();
aTimer.Interval = 60000; //every min
aTimer.Enabled = true;
aTimer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
aTimer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
TimeSpan ts = sw.Elapsed;
if (ts.TotalSeconds >= LongToRun.TotalSeconds)
{
aTimer.Stop();
return;
}
DoWork();
}
}
timer_Elapsed never is called... Am I going about this wrong?
Your Start procedure returns immediately after it started the timer and returns to your main program. The main program ends and the timer that was still running is finalized before it elapses.
Solution: make sure your program is running long enough for your timer to elapse.
The main program creates a System.Threading.ManualResetEvent before starting the timer
After starting the timer it waits for the ManualResetEvent to be set using ManualResetEvent.WaitOne()
At the end of your timer_elapsed function the function raises the event using ManualResetEvent.Set
The thread in the main program that waited for this event continues processing.
Another problem is that you subscribe to the event after you started your timer. This is probably not a cause of the problem, but neat code would be to subscribe before you start the timer.
By the way, the timer class implements IDisposable. This means that the designer of this class informs you he uses scarce resources that need to be freed as soon as possible. Consider Disposing the Timer class as soon as it is not needed anymore. The using (...) statement is ideal for this.
Using async-await would make your code much easier to read and to maintain.
Consider the following code:
public static void Main()
{
Thread.Sleep(TimeSpan.FromMinutes(2));
var myTask = Task.Run( () => WorkerTask())
Task.Wait(myTask);
}
private static TimeSpan longToRun = new TimeSpan.FromMinutes(5);
// easier to read than new TimeSpan(0,300,0));
public static async Task WorkerTask()
{
StopTime = DateTime.Now + longToRun;
// repeatedly wait a while and DoWork():
while (DateTime.Now < StopTime)
{
await Task.Delay(TimeSpan.FromMinutes(2);
DoWork();
}
}
That's all, No need for ManualResetEvents, no Stopwatches, no Timers nor timer_elapsed event handlers.
It is even quite easy to pass parameters to procedure WorkerTask(), and cancelling the event for instance because the operator presses < esc > is easy if you create a CancellationTokenSource and pass a CancellationToken to the WorkerTask as a parameter. In fact, that would make the code even more simpler:
public static void Main()
{
Thread.Sleep(TimeSpan.FromMinutes(2));
using (var tokenSource = new CancellationTokenSource())
{
var myTask = Task.Run( () => WorkerTask(tokenSource.Token))
tokenSource.CancelAfter(TimerSpan.FromMinutes(5));
// instead of LongToRun
Task.Wait(myTask);
}
}
public static async Task WorkerTask(CancellationToken token)
{
// repeatedly wait a while and DoWork():
while (!token.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(2, token);
DoWork();
}
}
More information:
MSDN Task Cancellation
Async await explained
As Sergey pointed out there is a mistake in the time period set in Timespan LongToRun. I have tried a cod with just Thread.sleep function. Hope the code is helpful for you.
class Program {
static System.Timers.Timer aTimer;
static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
static TimeSpan LongToRun = new TimeSpan(0,5,0); //run for 5 minutes
static void Main (string[] args) {
Console.WriteLine("Start Of Program" + DateTime.Now);
Thread.Sleep(120000); //sleep for 2 mins
sw.Reset();
sw.Start();
Start();
}
static void Start() {
TimeSpan ts = sw.Elapsed;
while (ts.TotalSeconds < LongToRun.TotalSeconds) {
doWork();
Thread.Sleep(60000);
ts = sw.Elapsed;
}
Console.WriteLine("End of program");
Console.ReadLine();
}
static void doWork() {
Console.WriteLine(DateTime.Now);
}
}
First of all, you've set incorrect period:
static TimeSpan LongToRun = new TimeSpan(0,**5**,0)); //run for 5 minutes
timer_Elapsed is never called because your application is closed earlier. Add Console.ReadLine() at the end.
static void Main (string[] args){
Thread.Sleep(120000); //sleep for 2 mins
sw.Reset();
sw.Start();
Start();
Console.ReadLine();
}
the timer needs to be run as a thread and it will trigger an event every fixed interval of time. How can we do it in c#?
Here's a short snippet that prints out a message every 10 seconds.
using System;
public class AClass
{
private System.Timers.Timer _timer;
private DateTime _startTime;
public void Start()
{
_startTime = DateTime.Now;
_timer = new System.Timers.Timer(1000*10); // 10 seconds
_timer.Elapsed += timer_Elapsed;
_timer.Enabled = true;
Console.WriteLine("Timer has started");
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan timeSinceStart = DateTime.Now - _startTime;
string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
Console.Write(output);
}
}
Use one of the multiple timers available. Systme.Timer as a generic one, there are others dpending on UI technology:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
You can check Why there are 5 Versions of Timer Classes in .NET? for an explanation of the differences.
if you need something with mroore precision (down to 1ms) you an use the native timerqueues - but that requies some interop coding (or a very basic understanding of google).
I prefer using Microsoft's Reactive Framework (Rx-Main in NuGet).
var subscription =
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(x =>
{
/* do something every second here */
});
And to stop the timer when not needed:
subscription.Dispose();
Super easy!
You can use System.Timers.Timer
Try This:
class Program
{
static System.Timers.Timer timer1 = new System.Timers.Timer();
static void Main(string[] args)
{
timer1.Interval = 1000;//one second
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
//do whatever you want
Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
}
}