How can I write a scheduler application in .NET? - c#

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.

Related

Event firing at specific time in C#, with precision to second

I'm currently writing a C# application that will schedule an event to be fired at a specific time. I started off using the Quartz library for scheduling the event, but my issue is that I need to guarantee that the event will fire within a given second, and Quartz does not offer that precision.
I could spawn a thread via Quartz a few minutes before the actual scheduled time, then just have a loop that tests if the current second is correct.
Is there a better way to do this?
Couple ways to do this:
If the application is running at all times, it can use a Timer to check if a specific time has come. If it has, it will fire the method/command to run. Here's some more basic info/tutorial on Timers: http://www.dotnetperls.com/timer
If you are wanting the event to fire when the application is not even running, you can look at creating a Task for the event you want it to perform. Link to creating a Task is here: Creating Scheduled Tasks

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 trigger an event at 03:00 every night?

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.

Global Timer in Asp.net

I would like to have a timer for an ASP.net application that will kick off every Sunday night and perform something (update a table in the database). However, I really don't want to write up a service that has to be deployed on the server in addition to the web application. Is there a way to accomplish this easily? Perhaps using a Global.asax file?
It seems that the best solution was to use this technique. If I had more control over the server I would probably write up a console app to take advantage of scheduled tasks.
I'm not 100% sure where you would put it, but using a System.Threading.Timer would rock this.
// In some constructor or method that runs when the app starts.
// 1st parameter is the callback to be run every iteration.
// 2nd parameter is optional parameters for the callback.
// 3rd parameter is telling the timer when to start.
// 4th parameter is telling the timer how often to run.
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerElapsed), null, new Timespan(0), new Timespan(24, 0, 0));
// The callback, no inside the method used above.
// This will run every 24 hours.
private void TimerElapsed(object o)
{
// Do stuff.
}
Initially, you'll have to determine when to start the timer the first time, or you can turn the site on at the time you want this timer running on Sunday night.
But as others said, use something other than the site to do this. It's way easy to make a Windows service to deal with this.
I would write a console app and use Scheduled Tasks to schedule it.
Try the Quartz .NET, a job scheduler for .NET enterprise application such as ASP .NET and this should serve your purpose.
I don't think a .NET application is a good solution to your problem.
IIS Recycling will recycle the process every few hours (depending on the setting) and even if you set that interval to seven days, the application pool can still be recycled for other reasons beyond your control.
I agree with jcrs3: Just write a little console app and use scheduler. You can also write a service, but if you need something quick and easy, go with the console app.
In response to your comment about Scheduled Tasks:
Another hack would be to override an event in Global.asax, an even that is called often like Application_EndRequest() and do something similar to:
protected void Application_EndRequest()
{
if (((DateTime)Application["lastTimeRun"]) < DateTime.Today)
{
Application["lastTimeRun"] = DateTime.Today;
doSomething();
}
}
This would run after the first request after the date changed, so you wouldn't be guaranteed that this would be run precisely at 3:00 AM every morning.
I've even seed cases where you would hit the site using a Scheduled Task on another computer.

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.

Categories

Resources