I am working on .net windows application.
I am using System.Threading.Thread.
In a single form using five(5) threads. I have a code which when run, it executes series of lines in sequence. I would like to add a pause in between.
For that i am using
Thread.Sleep(10800000)
of 3 hours
But I checked in debug mode, after executing line of
Thread.Sleep(10800000)
My debug not goes to next line or next line never executes even after waiting for 4 hours.
I am using this Thread.Delay in other thread not in main thread.
This delay requires because, i send a command to configure setting to a hardware, that setting requires minimum 3 hours to complete.
That's why i am using this
Thread.Delay(10800000)
Means my onward code is proceed only after waiting for 3 hours.
Can any one help me?
Thread.Sleep is not designed for long sleeps. You should consider using somthing like System.Threading.Timer.
Provides a mechanism for executing a method on a thread pool thread at specified intervals.
You can give it a first run time of midnight, and have it go off every 24 hours. the Timer(TimerCallback, Object, TimeSpan, TimeSpan) constructor is exactly what you are looking for.
One would argue that even using a timer is not the best tool for the job. You may want to consider using Windows Task Scheduler (TS) instead. With TS, you can setup a schedule to say run your app and carry out the workflow, or if your program must run all the time, trigger another process that communicates with your app somehow.
If the process is not doing anything until the next interval then it's best to just simply kill the app. That way you won't be wasting threads or processes twiddling their thumbs over exorbitant delays waiting for the next interval to do something.
You can use the Microsoft Task Scheduler v2 COM Library from c# to setup your schedules or do so manually from the TS UI itself.
Related
I am a newbie to dotnet, and I have a C# code in a Windows Service application which have to run for every 24hours. For specifying the interval I used the below code:
var t=new System.Threading.Timer(e=>method(),null,Timespan.Zero,TimeSpan.FromHours(24));
So the above line of code would check for the condition for every 24 hours.
My doubt is, what happens to the process in the mean time(like between 24 hours). Does it goes to sleep on its own? if so, is there any way to know if the process is at sleep
Does it goes to sleep on its own?
No, the current thread will continue to run, and do whatever you tell it to do. If you want the thread to sleep you need to tell it to sleep. And this is possibly what you should do for a console program, or trap it in a "press any key to continue" question.
If your application is an UI application there will be a main thread that listens for windows messages, in that case you should rarely if ever use Thread.Sleep on the UI thread.
The timer uses the OS to do the actual waiting, and this will eventually use some kind of hardware to raise timing events. When the timer elapses it will raise the event on the threadpool, so it may run concurrently with the thread that started the timer. Note that there are other timers that work slightly differently.
I am developing a Windows Service application, in .NET, which executes many functions (it is a WCF service host), and one of the targets is running scheduled tasks.
I chose to create a System.Threading.Timer for every operation, with a dueTime set to the next execution and no period to avoid reentrancy.
Every time the operation ends, it changes the dueTime to match the next scheduled execution.
Most of the operations are scheduled to run every minute, not all toghether but delayed by some seconds each other.
Now, after adding a number of operations, about 30, it seems that the timers start to be inaccurate, starting the operations many seconds late, or even minutes late.
I am running the operation logic directly in the callback method of the timer, so the running thread should be the same as the timer.
Should I create a Task to run the operation instead of running it in the callback method to improve accuracy?
Or should I use a single timer with a fixed (1 second) dueTime to check which operations need to be started?
I don't like this last option because it would be more difficult to handle reentrancy..
Timers fire on a thread pool thread, so you are probably finding that as you add lots of timers that you are exhausting the thread pool.
You could increase the size of the thread pool, or alternatively ensure you have fewer timers than the thread pool size.
Firing off Tasks from the callback likely won't help - since you are going to be fighting for threads from the same thread pool. Unless you use long-running tasks.
We usually setup multiple timers to handle different actions within a single service. We set the intervals and start, stop the timer on the Service Start/Stop/Shutdown events (and have a variable indicating the status for each one, i.e. bool Stopped)
When the timer ticks over, we stop the timer, run the processing (which may take a while depending on the process, i.e. may take longer than the interval if its short.. (this code needs to be in a try--catch so it keeps going on errors)
After the code has processed, we check the Stopped variable and if its not stopped we start the timer again (this handles the reentrancy that you've mentioned and allows the code to stick to the interval as much as possible)
Timers are generally more accurate after about 100ms as far as I know, but should be close enough for what you want to do.
We have run this concept for years, and it hasn't let us down.
If you running these tasks as a sub-system of an ASP.NET app, you should also look at HangFire, which can handle background processing, eliminating the need for the windows service.
How accurate do the timers need to be? you could always use a single timer and run multiple processing threads at the same time? or queue the calls to some operations if less critical.
Ok, I came to a decision: since I am not able to easily reproduce the behavior, I chose to solve the root problem and use the Service process to only:
serve WCF requests done by clients
schedule operations (which was problematic)
Every operation that could eat CPU is executed by another process, which is controlled directly by the main process (with System.Diagnostics.Process and its events) and communicates with it through WCF.
When I start the secondary process, I pass to it the PID of the main process through command line. If the latter gets killed, the Process.Exited event fires, and I can close the child process too.
This way the main service usually doesn't use much CPU time, and is free to schedule happily without delays.
Thanks to all who gave me some advices!
I'd like to implement a recurring functionality to do something that activates, say, every Monday.
What are the ways of doing this programmatically in a Window Forms application that runs continuously in a server?
I'm familiar with delays but I haven't implemented delays that span for a week or month.
In my opinion your best bet is to write this functionality in a Console app and create a task on the server using Scheduled Tasks (or SQL Scheduler, or your favorite Scheduling tool) to execute it at whatever interval you need.
I don't like to see apps have "hidden" tasks in the code that execute at a specific time. Too many opportunities to fail without notification.
With a scheduling tool you can view/change the schedule without having to touch source code.
As side notes, Windows Forms apps should run on the client, not on the server.
If you're app is already running anyways, what I would do is have a periodic task that checks whether you want to do your weekly task
here's psudocode to demonstrate the logic.
if(today is Monday && i didn't do this task yet today)
{
//do monday stuff
}
Ideally you should perform this operation under windows scheduled task. It will then take care of the recoccurrance as well as timing.
If you need to do this via a winforms application, then there are two options - periodic time polling or blocking wait/sleep.
With periodic time polling, you set a time interval in which the application must run. Then in a loop check if this period has elapsed, and take action. You can set the required level of accuracy in side the loop.
With blocking wait, you sleep the running thread until it is time to execute. The only issue with this approach is if the server restarts, the application should regain it's state and resume any sleep operations. The accuracy of this approach should be within a few seconds (depending on the time drift of your server).
I m able to build a windows service and install it.
I m curious how can i run this service every hour ? I want it to run every hour periodically.
I also need to know the hour range that it s running so that I can store it somewhere.
How can i do that?
Edit : This service will be installed on many machines, therefore, I dont want to create a scheduled task say on 100 servers.
If you want a task to run on a regular interval as opposed to constantly, you should look into using the Task Scheduler.
If you need your code to be a service, but to be "activated" every hour, the easiest approach would be to make your service a COM object and have a simple task scheduled every hour that invokes a jscript/vbscript that creates your COM object and calls simple method on it.
The alternative is to use any of the wait APIs to "waste" an hour without consuming cycles.
Note that you also have to consider some interesting design decisions that depend on what your scenario is:
how is your service going to be started if it crashes or is stopped by the user?
if you are started after more than an hour, should you run again or do you need to wait to get on the exact hourly schedule?
how do you keep track of the last "activation" time if the timezone or the day-light saving time has changed while you were not active?
does your service prevent the computer from going to sleep/hibernate on idling or when the laptop cover is closed? if not, do you need to awake the computer on the hour to get your service working on your schedule?
Some of those are taken care of by the task scheduler, so I would strongly recommend going that route vs. waiting for an hour in your code.
You could create a scheduled task that runs every hour, to either run the service or send a message to "wake it up". Then, either pass in the current time in the scheduled task request, or just have your program pick up the current time when it wakes up.
Task Scheduler Managed Wrapper can help you set this up programmatically; you can google for other resources as well.
There are a couple options.
You could sleep for an hour.
You might be better suited for a Scheduled Task, not a service.
Thread.Sleep(1000*60*60);
Thread.Sleep(TimeSpan.FromHours(1));
code more readable this way
Thread.Sleep() solution will make sure that your service will run in one hour intervals, not every hour i.e. each task will be started at 1 hour + time to run the task. Consider using a Timer within your service. This will be a more robust solution since you have a control when to run a task, monitor its progress etc. Just remember that each Timer event will be fired in a different thread and if the task takes longer than one hour to run you might have to wait for the first task to finish to avoid concurrent tasks.
Task schedulers may be a good idea but services are designed to do this. Services gets installed easily and logs things properly. All you need to do is, at start of service, you can install a system timer (System.Threading.Timer) or there is also one more timer.
How is this done best? I want an app that's running on a server to trigger an event every night at 03:00.
Use windows task scheduler
If you want to do this in running app code (instead of using a task scheduler), you should choose a duration to let your app sleep that's fairly long (e.g., 1 hour, or 3,600 sec). Your app loops, and as each sleep call expires, the app periodically checks how much time is left until the deadline time (03:00). Once the remaining sleep time gets below the coarse interval time, it should be reduced to a shorter interval (halved each time, or reduced to 10 sec). Continue the loop, sleeping and reducing the interval time, until the target deadline time is reached.
This prevents the loop from waking up too often (86,400 1-sec intervals is overkill), but it also prevents the app loop from overshooting the target deadline time by sleeping too long.
You could make a timer with an interval of 1 second and when the timer goes off, check if it's 3:00.
You'll need to build it in a service in order to ensure that it runs even if there's nobody logged into the machine, and then there are lots of different methods to ensure that the trigger occurs.
Consider making a System.Timers.Timer where the Interval is set to the difference between DateTime.Now and the next 3:00.
There are two basic options here.
If you're trying to do this within an existing service, you can use a Timer to trigger yourself at 3:00 each night, and run your "task".
That being said, this is typically better handled via Windows Task Scheduler. Instead of keeping the application alive 24/7, you just schedule it to run once every day at 3:00.
Edit:
If you need to work with the Task Scheduler from code (mentioned in another comment), that is also possible. The Task Scheduler provides an API for setting up individual Tasks (ITask) via the Task scheduler (ITaskScheduler).
However, given that you're working on XP Embedded, you're probably better off just using the normal system configuration capabilities, and setting up a task to run once each day. In an embedded system, you should have enough control during your deployment to do this.
Here is a simplified version of a service that we wrote that runs a timer every 60 seconds to watch a table... you could alter the timer elapse event to check the time and run it then:
Dim Timer As System.Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
Timer = New System.Timers.Timer(60000)
AddHandler Timer.Elapsed, AddressOf timer_Elapsed
Timer.Start()
End Sub
Protected Overrides Sub OnStop()
Timer2.Stop()
End Sub
Private Sub timer_Elapsed(ByVal pSender As Object, ByVal pargs As System.Timers.ElapsedEventArgs)
'Ensure the tick happens in the middle of the minute
If DateTime.Now.Second < 25 Then
Timer.Interval = 65000
ElseIf DateTime.Now.Second > 35 Then
Timer.Interval = 55000
ElseIf DateTime.Now.Second >= 25 And DateTime.Now.Second <= 35 Then
Timer.Interval = 60000
End If
'Logic goes here
End Sub
Obviously, if you can, use the task scheduler like everyone else here has mentioned. It is the preferred way of doing this. I just happened to have this code laying around so I thought I'd post it in case it could be helpful to you. Also, this code worked for us because we never knew when an external source was going to edit a table. Setting the interval to a correct number of milliseconds would be a much more efficient way of doing this, as pointed out by md5sum.
This answer might be a bit left field, but we often use CruiseControl.NET for some of our scheduled tasks. It's not perfect for them all, but if it's a big job that you want to run every night and other code/outcomes depend on it then it's a good choice. You can schedule it to run whenever, get emails if it worked/failed. Run other scripts/code if it did not work, clean up files you need before you start and after.
Not the perfect solution to all situation, but it is damn powerful for those that call for it. We use it for some of our big data processing jobs, and it sends us all an email if it worked/failed and will even try again 30 minutes later if it failed the first time. It gives you a nice fuzzy feeling :)
Windows task scheduler (as suggested by klausbyskov) or a SQL Server job.
EDIT:
Or if you want a dyanically assigned time, you could create a windows service that polls every 10 minutes and performs some action at the desired time(s).
Creating a windows server in C# is fairly trivial and could do this. Just make sure you've got the security and logging figured out because it can be pretty hard to tell what's going on while it is (or isn't) running.
Use System.Threading.Timer.
I'm spawning a thread in an ASP.NET application to do scheduled tasks.
It depends on what you have available to you.
Your best bet is to use a cron job, if you are on Linux/Unix/Mac OS X, a task scheduler on Windows, or launchd on newer versions of Mac OS X.
If you want to do this from within an application, you would need a loop that checks the time on a regular basis and fires off the event if it is 03:00, but this isn't ideal.
Is the program able to run via command line? If so, create a foo.bat file, and call your program command line (very simple).
Then use Task Scheduler to run the .bat file at 3 a.m. daily.