Checking a condition every minute on a WebAPI application - c#

I'm learning basic web application development using Microsoft WebAPI. I've created a drinks ordering service where users order drinks, post it to the server, and the server stores them for later.
Users post their order to a RESTful endpoint on an OrdersController. The endpoint stores the order in a list and checks the list against a condition. E.g, "Are number of orders > 5?"). If satisfied, the server sends a push notification to the users' mobile phones using the Google Cloud Messaging service.
I wish to expand the type of conditions that could trigger a push message. For example, "If no orders have been received in the last 5 minutes, send a push notification". In other words, I would need to check the condition more often than just in response to receiving a new order request.
What is the best way to accomplish this? My initial thought was just to create a Timer which runs the condition checking method at intervals, but a search of stack overflow has suggested that this kind of approach might be a bad idea.

I have several ideas depending on the hosting environment:
If it's your server (virtual or otherwise)
Create a seperate application that runs as a windows service or a windows application that handles that process seperately from the webAPI.
If running on Azure as a Cloud Application you can create a web worker role that is scheduled to run every so many minutes and could then query and process items.
If you only have a hosting enviornment for MVC/WebAPI then you could look into the cache/callback trick. You basically add an entry to the cache when a callback to a method.
a. Create a controller method that adds a cache entry with a callback to a method
b. The method does whatever work it need to do then calls the controller action so another entry is placed in the cache.
Each time the cache times out, it calls the callback method which you can use to process information and then call the controller method to start the process over again.
When I was experimenting with this, I created a small scheduling project that looped through a list of tasks. Each task was responsible for determing if they any processing was needed. Amazingly enough it worked well and the server never shuts down the process.
Keep in mind if your hosting in the cloud that this will simulate activity and memory usage which could cost you some amount of money, although I would think it would be trival.
I've heard they are scheduling solutions, possible even a monitoring service that can call a WebAPI endpoint every so many minutes which could work much like the callback method. You could check for the need to process each time the monitoring service calls the endpoint.

You can use Reactive Extensions: it lets you program time-related events in a declarative manner without having to bother with handling timeouts and tracking. You can even test your setup by controlling time itself!
For example, to trigger an event after some inactivity, you could use the Timeout method of an observable. The Buffer method can let group trigger an event after x drinks have been ordered, etc

In general what you describe sounds like a backend task/responsibility. You can consider this library HangFire.io to safely perform this operation from ASP.NET - http://hangfire.io/
The other way you could simulate event firing from with ASP.NET for simple one-off cases is , is you can you can use the built-in cache and its expiration event.

Related

How to do a specific proccess per in month in asp.net mvc?

I am trying to write a website and now I need to do a specific method one per month(at the end of the every month).
Imagine that the method is Method A().
I want to run it at the end of the every month.
So now how to run it ?
UPDATE:
The mission of the website is something else.Just in a part of it I need to do this.
I dont know but I guess maybe running the method in application start at the end of the every month can solve it but I am not sure that its the way or not.
ASP.NET MVC is for writing web applications, not scheduled tasks.
Web applications are architected as request/response systems. They are not suited for background tasks which need to happen at regular intervals. They receive a request, respond to that request, and are done. While idle a web application is subject to the web server's resource management, which could include shutting it down entirely while waiting for the next request.
Instead, what you'll want to use is either a Windows Service or a Console Application (invoked by a task scheduler, such as the one that comes with Windows). This would run continuously in the background or at regular intervals, respectively. This application can be very small, just calling that one method and nothing else.
In short... If you want to run the code in response to a user request then a web application will do the job. If you want to run the code at regular intervals regardless of user requests then a scheduled task is what you want.
Well, that seems like something that doesn't belong on the web site. i.e. it shouldn't be run within ASP.NET anywhere. Maybe it should be run in a back office, or a service that's running on the back end or a database job or a scheduled task. But if all you have is the one job, it would probably be easier to have a button that when pushed calls the method A(), and have it in a logged in portion of the website with some sort rights check to ensure no one but the correct people press it. And you could also put checks, within the method to ensure it's only run once a month. If you can be sure that the rest of the website is being used, you could put in other methods a CheckToSeeIfIShouldCallMethodA method, but all of these seem like worse options than something that runs on the back end.

Scheduling job idea needed by the web application in asp.net

I have written a web application in asp.net. It has some user roles. There are 3 roles which are Manager, Accountant and Employee. The employees write their expenses in a form and send it to Manager. When manager approves it, it'll be sent to Accountant to pay it. I need to have an idea that when manager doesn't approve the employee's expense in 48 hours, it should send an automatic e-mail to Manager's mail.
I thought that I can write another small console application to handle that by checking every hour. But it would waste resources and decrease performance.
I need a good idea to handle that. How should I do?
There are several options, but if I were you I would go with first or second options.
Console App & scheduler
I would create that console application that every time is run perform the check for you.
Then I will have it run using Windows Scheduler in a daily basis (at 00:05) or a hourly basis if you prefer so. This way Windows Scheduler daemon will launch it every hour and the rest of the time your app is not running.
Check this Microsoft link to see how a scheduled task is created in windows.
Restful Web Service & scheduler
As suggested in #marapet answer, having a restful web service that allow you to perform this action instead of a console application would give you the advantage of having all code in your web application.
Similar as previous one, you should only invoke the restful uri to have your action done. As possible disadvantage, you have to get sure that that uri is not accessible to end users. In usual architecture (Web Server --> Application Server --> DB) this restful service should be in the Application Servers, far away from end user access.
Windows Service
Another option is creating a Windows Service that runs all the time and check the time itself so every hour perform the job (maybe using Quartz or similar). But this does not meet your performance requirements.
The performance hit will be small anyway as your service should check every minute to see if an hour has pass and is time to do its job.. a task pretty easy.
The advantage is that a windows service is easier to control and monitor than a Scheduled tasks
DB job
Yet another option... If your app uses SQL Server you can have a t-sql job that runs daily or hourly. I wouldn't recommend this option unless you really have performance problems.
The problem with this is that you would be splitting the logic and responsibilities of your code. A future developer or admin would find hard to maintain your app.
If you'd like to keep the logic within the web application for simplicity (depending on the total size of your solution, this may or may not be desired):
For a given URL, have the web app check for due approvals and sends emails out if needed. Be sure to keep track of emails sent in order to prevent sending the same email multiple times.
Call this URL in a regular interval. You may use a scheduled task or a third party url monitoring service to do this.
You may call the URL with a simple VBScript (or wget, or curl, or powershell, or whatever is fastest for you), which in turn you can automate by using the task scheduler (see also).
An example script in vbscript for calling an URL:
Function LoadUrl(url)
Dim objRequest
Set objRequest = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objRequest.open "POST", url , false
objRequest.Send
LoadUrl = objRequest.responseText
Set objRequest = Nothing
End Function
Checking every hour won't affect performance. Even checking every minute is probably fine, depending on your database. The simplest option is a console program fired as a Scheduled Task. You can also try a Windows Service but they're a bit trickier.
Also give some thought how you'll count the 48 hours. If an employee puts in expenses just before the weekend then 48 hours will probably elapse every time and you'll end up with a manager having lots of emails in their Inbox on Monday morning. That could cause some friction :)

Start a long running job with a web service call

We have a data transfer between 2 systems that can take upto a few hours. The code for doing this transfer is written in C#.
We would like to trigger the transfer with a WCF web service call.
Ideally we would like the web service call to return at once, with a message "OK job started", and then the job to run on the server untill it is complete.
What is the best way to do this?
The possible problems we see are:
web service timing out before job finished
job stops after returning result
Although not entirely similar to your predicament, I had a similar scenario with my MVC application. There are lots of "Jobs" to do that involve importing data, batch emails, financial processes etc.
Basically, I created a windows service which had a job manager, and obviously the various jobs that could be done. It also ran a light HttpServer. This allowed the main MVC application to talk to the service. One sends a request to start jobs and get the status of all jobs or a particular job (when a job is started it is given a unique ID).
So if I was going to implement it in your case, I'd add a download job which did the actual work, and instigate it from the MVC App via a JSON call. The status of the download could be queried at any time by using the ID passed back from the "StartJob" JSON call. Your main web request is therefore handled and over immediately.
I'd write a console application that does this job and let the Web Service call that application.
Running heavy processes within the web server itself is never a good idea.
You may use background thread on the WebServce call.

Schedule method invocation C#

I'm using c# to communicate with twitter and i need to code a schedule system to send twitter messages at a user defined date.
The messages to be sent are in a database with the date and time of deliver.
Which is the best method to check the db for scheduled messages and send it when the time arrives?
How accurate do you need the timing to be? Could you get away with polling the database every 5 minutes, saying "Tell me all the messages which need to be delivered before current time + 5 minutes" and then sending them all? (And marking them as sent in the database, of course.) Does it matter if they're a bit early or late?
You can do the scheduling on the C# side to make it more accurate, but unless you really need to I'd stick with a very simple solution.
(Depending on your database there may be clever ways of getting callbacks triggered etc... but again, I'd stick with the simplest solution which works.)
In addition to the windows service option (or background thread), you could just set up a scheduled task to run an app that polls the DB and sends the tweets once every defined interval.
Windows schedules can be setup using C# if needed and are really easy to set up manually.
There are several ways to do this, but I guess the best way is to set up a Windows Service that will periodically poll (frequency is up to you) the DB for any scheduled tweets that hasn't been sent.
Needless to say you'll need to handle scenarios such as the Internet connection or DB being down, etc.
In fact the solution consists in using a windows service but it can't communicate directly with the ASP.NET MVC app. I've added a Web Service that handles the task and a System.Threading.Timer in Windows Service to periodically call the Web Service.

Best approach to fire Thread/Process under IIS/WCF, in a shared hosting

Scenario: A WCF service receives an XDocument from clients, processes it and inserts a row in an MS SQL Table.
Multiple clients could be calling the WCF service simultaneously. The call usually doesn't take long (a few secs).
Now I need something to poll the SQL Table and run another set of processes in an asynchronous way.
The 2nd process doesn't have to callback anything nor is related to the WCF in any way. It just needs to read the table and perform a series of methods and maybe a Web Service call (if there are records of course), but that's all.
The WCF service clients consuming the above mentioned service have no idea of this and don't care about it.
I've read about this question in StackOverflow and I also know that a Windows Service would be ideal, but this WCF Service will be hosted on a Shared Hosting (discountasp or similar) and therefore, installing a Windows Service will not be an option (as far as I know).
Given that the architecture is fixed (I.E.: I cannot change the table, it comes from a legacy format, nor change the mechanism of the WCF Service), what would be your suggestion to poll/process this table?
I'd say I need it to check every 10 minutes or so. It doesn't need to be instant.
Thanks.
Cheat. Expose this process as another WCF service and fire a go command from a box under your control at a scheduled time.
Whilst you can fire up background threads in WCF, or use cache expiry as a poor man's scheduler those will stop when your app pool recycles until the next hit on your web site and the app pool spins up again. At least firing the request from a machine you control means you know the app pool will come back up every 10 minutes or so because you've sent a request in its direction.
A web application is not suited at all to be running something at a fixed interval. If there are no requests coming in, there is no code running in the application, and if the application is inactive for a while the IIS can decide to shut it down completely until the next request comes in.
For some applications it isn't at all important that something is run at a specific interval, only that it has been run recently. If that is the case for your application then you could just keep track of when the table was last polled, and for every request check if enough time has passed for the table to be polled again.
If you have access to administer the database, there is a scheduler in SQL Server. It can run queries, stored procedures, and even start processes if you have permission (which is very unlikely on a shared hosting, though).
If you need the code on a specific interval, and you can't access the server to schedule it or run it as a service, or can't use the SQL Server scheduler, it's simply not doable.
Make you application pool "always active" and do whatever you want with your threads.

Categories

Resources