How to trigger an event at 03:00 every night? - c#

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.

Related

Issue regarding Thread.Sleep() for 2hours in c#

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.

Windows Service needs to wait, Thread.Sleep?

I have a c# windows service that needs to execute a database query every 60 seconds (or whatever interval is set in the config file). I'm using Thread.sleep(60) in a while loop to accomplish this. Is there a better way to do this?
Thanks
You can use a System.Threading.Timer to run your code every 60 seconds instead of doing it in a sleeping thread.
It depends on what you want to do. If you want a (more) exact method you may want to use System.Threading.Timer. One thing about thread.sleep is that it really is "sleepatleastuntil...". The processor will ignore your thread until the sleep time is past. The next time it would give your thread priority, after the sleep time is past, it will.
This will normally be very close to the desired interval, but could be longer. Don't yield unless you really intend to yield.
Use a Timer to fire the process every 60 seconds rather than force the process to sleep.

Windows service that will run every hour

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 to run automatic "jobs" in asp.net?

I want to have my website do a number of calculations every 10 minutes and then update a database with the results. How exactly do I set such a timer, i am assuming it would be in global.asax?
Doing something like that in a web application is somewhere between difficult and unstable to impossible. Web applications are simply not meant to be run non-stop, only to reply to requests.
Do you really need to do the calculations every ten minutes? I have found that in most cases when someone asks a question like this, they really just need the appearence of something running at an interval, but as long as noone is visiting the page to see the results, the results doesn't really need to be calculated.
If this is true in your case also, then you just need to keep track of when the calculations were done the last time, and for every request check if enough time has gone by to recalculate.
You'd be better off writing a separate non-UI application and then running that as a scheduled task.
Aside from (correct) statements about instability of web application for scheduled task execution, here's a strategy you could implement:
in global.asax, define application.onstart event in which create timer:
var dueTime = 5000;
var period = 5000;
var MyTimer = new Timer(new TimerCallback(MyClass.MyTaskProc), null, dueTime, period);
Application["MyTaskTimer"] = MyTimer;
this will pretty much take care of creating task and restarting it should application exit
ifs its strictly database calculations, keep it in the database. Create a stored proc that does what you want, then have SQL Server agent run that proc on a schedule.
the Cache solution in cagdas' answer works. I've used it. It's only downside is that it's difficult to turn it off if you need to suspend the timer for some reason. Alternate, but not quite identical solutions we've used.
Scheduled tasks in SQL Server
Scheduled windows tasks.
I really don't like schecduled tasks. I would rather put this function in a windows servic and throw a timer in it. With window services you can handle stop events very nicely. I do agree with everyone else, the web site is not the place for this.

How can I write a scheduler application in .NET?

How can I write a scheduler application in C# .NET?
You could also try Quartz.Net.
It all depends on your requirements:
If you have access to a database you use a table as a queue and a service to poll the queue at regular intervals.
If your application is client only (CLI) you can use the system scheduler ("Scheduled Tasks").
Lastly, if your application is only in a database (using the CLR in SQL Server 2005 for example) then you can create a SQL Server job to schedule it.
Assuming you're writing some system that needs to perform an action at a specific clock time, the following would cover the fundamental task of raising an event.
Create a System.Timer for each event to be scheduled (wrap in an object that contains the parameters for the event). Set the timer by calculating the milliseconds until the event is supposed to happen. EG:
// Set event to occur on October 1st, 2008 at 12:30pm.
DateTime eventStarts = new DateTime(2008,10,1,12,30,00);
Timer timer = new Timer((eventStarts - DateTime.Now).TotalMilliseconds);
Since you didn't go into detail, the rest would be up to you; handle the timer.Elapsed event to do what you want, and write the application as a Windows Service or standalone or whatever.
Write a windows service, there are excellent help topics on MSDN about what you need to do in order to make it installable etc.
Next, add a timer to your project. Not a Winforms timer, those don't work in Windows Services. You'll notice this when the events don't fire. Figure out what your required timer resolution is - in other words, if you have something scheduled to start at midnight, is it Ok if it starts sometime between Midnight and 12:15AM? In production you'll set your timer to fire every X minutes, where X is whatever you can afford.
Finally, when I do this I use a Switch statement and an enum to make a state machine, which has states like "Starting", "Fatal Error", "Timer Elapsed / scan for work to do", and "Working". (I divide the above X by two, since it takes two Xs to actually do work.)
That may not be the best way of doing it, but I've done it that way a couple of times now and it has worked for me.
You can try use Windows Task Scheduler API
You can also use the timer control to have the program fire of whatever event you want every X ticks, or even just one. The best solution really depends on what you're tring to accomplish though.

Categories

Resources