Scheduling Task for future execution - c#

I have looked at the Task and Timer class API's, but could not find information on how to schedule a Task for future execution.
Using the Timer class, I can schedule threads for future execution, but I need to schedule Tasks.
Task has .Delay(...) methods, but not sure delay is similar to scheduling.
Edit(clarification): I want to start tasks after x minutes.

You should use Task.Delay (which internally is implemented using a System.Threading.Timer):
async Task Foo()
{
await Task.Delay(TimeSpan.FromMinutes(30));
// Do something
}
While the delay is "executed" there is no thread being used. When the wait ends the work after it would be scheduled for execution.

I would use this Timer (System.Timers.Timer) instead. It's a bit simpler to use. Set the interval to 30 and start the timer, making sure the elapsed event calls the method you want to happen. You can stop it afterwards if you only want it to happen once and not every thirty minutes.
Code sample from the linked MSDN page:
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.Enabled = true;

//schedule stuff to run after 2 seconds
Task.Delay(2000).ContinueWith(t => {
//do something
});

Related

Stop creating new thread while system.timers.timer elapsed called

I am facing a issue when used to system.timers.time, i have a running process in my application.
with timer called my process start, but i want to use that process within the thread only.
because every time timer elapsed event called the new thread has been generated, but i want to prevent this and only using single thread in a process.
Here is my code.
Public void Watcher()
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 3000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
Public void OnTimedEvent
{
// process code here
}
Here, after every 3 seconds OnTimedEvent called and new thread created, but i don't want to create new thread every time.
So, how to prevent this, any idea?
If you have a UI you should simply use forms timer or dispatch timer. If you do not have a UI you can set the SynchronizationObject of the timer. This will be responsible for marshaling the execution to the right thread.
I would probably skip the synchronization object, and just do the marshaling in the event handler of the event.
In either case you will need some kind of message loop if you do not have a UI. This would have a threadsafe queue where the thread takes a message and process it, one at a time. For example, using a blocking collection of Action.
As mentioned by #MindSwipe in the comments. A new thread will not be generated per event. It will simply take threads from the threadpool. So the number of threads used should be fairly constant. The main reason for moving all execution to one thread is because it can make threadsafety easier to manage.

Pausable Timer on separate thread

I need timer running on separate thread that can be paused and resumed.
The System.Threading.Timer would be ok. but I notice that it spawns new threads even while I'm debugging the callback. I don't want next callback to started before first one is finished, I would like to pause the timer during execution of the callback.
The System.Threading.Timer cannot be paused.
I'm not going to measure any time so no System.Diagnostics.Stopwatch.
In this qestion someone implemented his own class deriving from Timer but I have no idea what timer is this - the System.Threading.Timer is sealed.
System.Windows.Threading.DispatcherTimer can be stopped but the callback is dispatched on UI thread and I'm not sure about portability of this class.
What should I do?
You could instead of using a timer just make it a loop with a delay:
public static async Task RepeatingTask()
{
while(true)
{
Console.WriteLine( "Doing cool stuff" );
await Task.Delay( 2000 );
}
}
And you can start it like this:
Task.Run( RepeatingTask );
NOTE: this will not do the trick if you need to fire every say 2 seconds exactly.

From AS3 to C# a simple elapsed Timer

I need to set up a simple elapsed Timer in C# (MonoBehavior) that calls a method when complete, but can also be cancelled before finishing. If cancelled or stopped, it automatically resets its interval. I don't need anything fancy like threading.
Reading over the documentation on C# Timers https://msdn.microsoft.com/en-us/library/System.Timers.Timer%28v=vs.110%29.aspxstill a bit confused. For instance, when you set mytimer.Enabled=false does it also reset the timer back to 0? Perhaps I should be looking at Coroutines instead?(this is for Unity)
In AS3 I would do something like this
private var _delayTimer:Timer;
//create a Timer object that runs once for 1 second
_delayTimer = new Timer(1000,1);
//add handler
_delayTimer.addEventListener(TimerEvent.COMPLETE, onDelay);
//start timer
_delayTimer.start();
private function onDelay(e:TimerEvent):void{
trace('delay finished!);
}
//some other method to interrupt-stop and reset the delay timer
private function foo():void{
_delayTimer.reset();
}
By using System.Timers.Timer, you are using multi-threading - it's quite likely this is not what you want.
Instead, you probably want System.Windows.Forms.Timer - this will post the timer event back on the UI thread (if you're using Windows Forms, of course).
You can use Start and Stop the way you want, because there's actually no ticking clock - it just registers a callback from Windows in the future, basically.
Relevant piece of documentation from MSDN:
Calling Start after you have disabled a Timer by calling Stop will cause the Timer to restart the interrupted interval. If your Timer is set for a 5000-millisecond interval, and you call Stop at around 3000 milliseconds, calling Start will cause the Timer to wait 5000 milliseconds before raising the Tick event.

How to make async pause in C#?

I have a program written in C# (Visual Studio), that works on a tray.
I want it to do one action every 10 minutes.
I have following code now:
while(true)
{
Thread.Sleep(10000);
// my stuff
}
But it doesn't work. It freezes a program.
You should use the timer object and not create a while loop.
System.Timers.Timer _timer = new System.Timers.Timer();
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
//30 seconds
_timer.Interval = 30000;
_timer.Start();
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
//do your logic
}
Thread.Sleep makes the calling thead Sleep for an X ammount of time. If this thread is the frontend thread (the one responsible for handling messages), it will indeed freeze the application since any message for handling events or repainting wont be handeled untill the Thread wakes up again and gets a chance of handling the messages.
What you should do is schedule this logic every 10 seconds.
Drop a timer on your form and specify it to run each 10 seconds. Within the Tick event, call your custom action.
Thread.Sleep "stops" the current thread. if you only have one thread, everything is paused.
What do you want to achieve ?
Perhaps you need a second thread, or perhaps the better solution a timer which triggers a action every 10 minutes
s. Task.StartNew() or ThreadPool

c# console app using thread

I have a console app. I need to implement a do while that loop infinitely and a thread that at every 3 seconds returns a list of items from a page. How can I do that? I have a methold called getId( string URL) . how do I implement the thread in the do while?
Using System.Timers.Timer class:
string url = "www";
System.Timers.Timer timer = new System.Timers.Timer(3000);
timer.Elapsed += (o, e) => this.GetId(url);
timer.Start();
Timer is designed for use with worker threads in a
multithreaded environment. Server timers can move among threads to
handle the raised Elapsed event, resulting in more accuracy than
Windows timers in raising the event on time.
The Timer component raises the Elapsed event, based on the value of
the Interval property
I would not use a timer - what happens if the item retrieval takes longer than three seconds?
Can you live with a sleep(3000) loop?
Rgds,
Martin

Categories