Scheduled tasks in one application (.Net C#) - c#

I got a database of subscriptions, I want to run a for every subscriptions from one time to another every x minute.
But every subscription has its own from and to time + what every x minutes its should run the function.
Its can be many subscriptions running the same time.
Maybe its should looks like a scheduled task that starting at one specific time and runs every x minute to one specific time.
I hope I describe what I want to do right, my English is not the best.
Do anyone has any idea how I building the application todo this?

You have a couple of choices here:
Use the SQL Agent and setup jobs with the required schedule (of course, this assumes you are using SQL Server).
Write a Windows Service with a timer that queries your database and executes the different tasks as needed.
You mentioned scheduled tasks, which might be another option, but that will require you to automate the setting up of new tasks as well as the actual tasks to run. Both of these are easier to do with the options I have outlined above.

I would recommend you to use System.Threading.Timer for that. To schedule a job, do the following:
new Timer(_ => DoTheJob()).Change(your_interval_in_milliseconds, Timeout.Infinite);
then when job is done, schedule next run using the same code. That would prevent running 2 instances of the same job simultaneously.
Please let me know if that does not answer your question appropriately.

You are maybe describing just what Quartz.NET can do for you. Check it out, it might be worth spending some time.

So you should write some kind of scheduler. It will take tasks from the queue and execute them... You can create a scheduler in such a way that every task for example will run in a separate thread and it would significantly improve performance!

Related

Ways to implement a recurring functionality?

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).

how to create and run cron job in asp.net page to run every 30 minutes

I need some guidance on creating and running a Cron Job in asp.net(C#.net) to run my page every 30 minutes. My Web page has to load data from Sql Server to MySql database every 30 minutes with this cron job.
Thanks
I don't think this is best suited for ASP.NET. You might want to just create a regular Console App, configure it in the Server Task Scheduler to run every 30 minutes. Or if you so inclined, you can create your own Windows Service to do this.
I don't think you'll find that feature out-of-the-box in ASP.NET. Here's what I usually do...
Setup a database table to track jobs, including the last time that each job ran.
In Global.asax's Application_Start event, I spin up a new .NET Thread, which runs a job checking loop.
In this loop, check your known jobs, check the database for the last run time, and then decide if it's time to run the job again. Run the job, update the database.
Sleep the thread for a bit. Continue the loop.
Be aware of the what-if's.
What if a task fails in your job loop, throwing an exception.
What if your in a server farm, and need to prevent multiple application instances from running the same task at the same time.
This is just something to get you started. Making this robust (if you need it robust) can get complicated.
Try investigating quartz.net, which is an open source port of the quartz project. I believe you should be able to include it as part of your web application.

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.

Executing an application after a period of time

I'm writing a small app that needs to be executed once a week.
I could write it as a service that runs constantly but only executes the task that I need it to once a week, but that seems like overkill.
Is there another way of executing an application once every x period of time?
I'm looking for a solution that doesn't involve user interaction.
You can always use Windows Scheduled Tasks. They can be ugly, but effective.
You could use the Windows Task Scheduler. It was designed with this scenario in mind.
You can use Windows Scheduler for planning execute app once a week.
Under windows you can use the at utility.
You can use the Windows Task Scheduler in the Control Panel. Just set up a task to run your application on the specified day. You can even tell it to run as a certain user if you want.
If you need full control on the process (result values, parameters to be provided, etc), I would suggest you to create your own task scheduler, where you can use the cron algorithm to schedule the time you want execute your task.
I know it may sounds overkill to create a service to run once a week, but if you make a generic scheduler, you will be able to reuse your schedule for other purposes.
I created this scheduler in the past, and it has been used for years in production. I implemented the cron algorithm in .Net, based in the open source algorithm that one developer (Artif Aziz) wrote. Check out my blog for more information on this:
CronTab schedule parser algorithm
If you think in a higher level (enterprise level), you could consider buying Control-M, one of the most powerful scheduler tools I have ever used, however it is quite expensive.
Cheers!
Roberto.

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