Use of timers to run an if statement hourly - c#

I have been reading loads about timers, and options for achieving my goal, and I believe I need to use system.timers.timer and set the interval correctly.
I think I know how to do this but what I am unsure of is where to do it, do I do so in my view, my controller, global.asax?
Maybe I shouldn't use a timer at all?
What I'm looking for is the best way to run an if statement on the hour, every hour, and update the view depending on the results of that if

Usually a web app (MVC or WebForms) isn't the best place to run scheduled tasks. It can be done, but you will get things like IIS recycling application pools and other anomalies, which although useful to a web app, could get in the way of reliably scheduling tasks.
A lot of developers (and my favourite too) schedule their tasks in a Windows Service. This can be installed and can be set to gracefully start and stop when the server starts and shuts down. You can then set up logging and other health monitoring to monitor the state of your scheduler service.
However if your tasks is purely SQL based you may wish to use SQL Server's inbuilt scheduling (or similar for any other database). Another alternative is to use the operating system's scheduler.
Edit
In regard to updating your view with the results, you can store and update the status of your scheduled tasks in the database with columns like 'TaskStatus' (New, Waiting, Running, Aborted, Failed, Cancelled, Completed) and 'TaskResult' (probably empty for success or the error message from a failure). You can then show and filter this information on your results view by retrieving it from the database.

JavaScript - On Your Page:
You can redirect to the controller > action that is your required function through JavaScript:
<script type="text/JavaScript">
setTimeout("location.href = '/YourDefineUrlPathHere';",1500);
</script>
HTML Meta tag - On Your Page:
Other is you can do it through meta tag if you want to call your view action again (in other words refresh it)
<head>
<meta http-equiv="Refresh" content="15;url='/YourDefineUrlPathHere'">
<!—‘15’ is number of seconds you want to wait-- >
</head>
Timers – in your controller
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(YourMethodHere);
aTimer.Interval = 2000;
aTimer.Enabled = true;
See MSDN: Timer
Timers are not very efficient solution if you want to keep caaling for a long amount of time
However another way and I guess more ‘standard’ way to achieve your result could be through Window Services if you want to pursue it in this direction this link might help you a lot.
Introduction to Windows Service Applications

What do you mean by "update the view"?
An MVC View is a class - you can only "update" objects as they have values. Views are instantiated when a user requests the page.
If you mean you want the user to have a page open in their browser all the time and it gets refreshed every hour, then you could use a timer in javascript on the client to reload the page every hour.
If you mean you want to update the results of any user opening your page depending on data that changes every hour, you can store the last update time in your database and then when the view runs check if the data is more than an hour old. If it is, run your if statement in your controller.

Use Azure Functions. You can run scheduled tasks using a timer trigger. It's pretty good.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview

Related

Firing events on regular time intervals (coming from database) using ASP.Net C#

Please check the image below.
Below I have a simple lottery system where I have these columns,
Vistors : Total no visitors till date
Next DrawTime : Will come from database (no problem with this)
TodayDate : Current IST Date(noproblem with this)
CurrentTime: Current IST time with seconds ticking like clock.
Result
TimeToDraw : Here we have main problem. Here we need is again ticker with minutes and seconds. For example if its get 15mins from db then the field will display 15:00 and on each second it will get decremented like 14:59,14:58... and so on. when the timer reach zero 00:00, i need to execute some server side code that will draw the result based on data saved in db, without reloading the entire page.
I am feeling lost. Please help me.
I have tried few links , but did'nt get any satisfactory result. Here are the links
Call js-function using JQuery timer
http://r4r.co.in/asp.net/01/tutorial/asp.net/How%20to%20make%20CountDown%20Timer%20in%20ASP.NET%20Using%20c-sharp.shtml
Javascript event triggers based on local clock
How to periodically update server-side value on webpage?
Requirements (Update):
Implementation of Minutes:Second(MM:SS) ticker using server side or client side scripts.
How to fire event when the ticker reaches zero(00:00)?
Again after drawing result, ticker will get reset to 15 min/30 min or whatever coming from database.
Please I need purely ASP.Net and C# (if possible) code. Any reference or link will be higly appreciated.
Thanks in Advance
Do NOT poll the server every second, that will create too much unneeded trafic.
Put a timer in the page (javascript) and when the timer reaches 0 poll the server.
The server should keep track of the time by itself; not relying on the client to provide the (potentially spoofed) time and pass back the appropriate response either winning tickets or nothing if it's not time yet to draw.
If you really need/want to push information from a server to the clients I recommend having a look at the suggestions here: https://stackoverflow.com/questions/6883540/http-server-to-client-push-technologies-standards-libraries
For SignalR have a look at this sample it is very close to what you need.
Do NOT use server side code to update the time on webpage unless it is critical.
For the countdown script look at the answer to this question: Javascript Countdown
When the timer reaches zero, refresh the page or execute an Ajax call using jQuery. When the call returns update the page depending on the server's response.
If you need more explicit answers you need to show what you have tried and point out problems you are having.

How to dynamically run process in asp.net

I am designing a website and it uses Windows Forms (in Visual Studio 10) in which for example i have five-six URLs. Now i am displaying them on home page of my website xyz.com
What i want is, i want to calculate total no. of tweets for all links and display links based on no. of times they are being tweeted/retweeted.
for a url we can calculate no. of tweet using twitter api http://urls.api.twitter.com/1/urls/count.json?url=YourURL
I know all the stuff like receiving JSON values in a string and parsing json to retrieve tweet counts and then compare and display links based on the priority etc.
What i have been using till now it is initiating all the process using a Click_Button.
But i want to know how can i automate this all for each 10 minutes. Its like a end user can see urls priority with just refreshing the page.
One way to do this is to run a scheduled task ever 10 mins which interacts with the DB. The web application also interacts with the DB and thus the two systems are distinct.
Side note: it is strongly recommended to use only console applications as scheduled tasks. If you make a windows form application will will have some issues.
As Kieren Johnstone has pointed out in another answer the best way to do this would be to write a windows service.
I still recommend the solution as described above as a first step since it is easy to debug and test.
Additionally, give some serious consideration to logging and error reporting -- with background tasks you can never know to much about what the heck it was doing when it broke.
If timing itself is not important (it doesn't have to be 10 minutes precisely), I would suggest binding to any event that fires when users use your application. No point in calculating anything if noone is using it :-)
So you could use a login, or page load, or whatever happens at an interval roughly like the interval you wish to achieve.
You can always store a DateTime variable somewhere that you can check to see when the calculation was last made. Something like:
public void MyEventHasFired()
{
DateTime dateLastProcessed = ... //Database? Session data? Anything goes.
if(dateLastProcessed < DateTime.Now.AddMinutes(-10))
{
//calculate
...
dateLastProcessed = DateTime.Now;
}
}
The best solution is definitely a Windows Service. It can be started, stopped and managed well, it's easy to log, maintain..
Scheduled Tasks are very prone to problems. At least in a Windows Service you can configure it to start automatically, re-start if there's a problem, you can control the timing yourself in the code, and catch/handle exceptions as you wish.
The best scheduler i know is Quartz.net
It'is not simple to use but it works great.
You can find an example with asp.net there http://blogs.planetcloud.co.uk/mygreatdiscovery/post/ASPNET-Scheduled-Tasks-with-QuartzNET.aspx
Anyway i agree with Kieren Johnstone: you should use a windows service

How can i automatically have a page save the current time to the DB in 5 minute intervals w/o postback?

Basically i have a C# Web App where a user views a streaming video. While they are viewing it, i have a timer running in the code behind. When they finish viewing the video, they hit a submit button which takes the difference from the start time and end time and emails the total viewing time to me.
The issue is, if they lose their session or their internet connection drops out for a brief moment, the time is lost and i have no proof how long they viewed the 1.5 hour video for.
I was wondering where to start to have it automatically save the time to the database like every 5 minutes behind the scenes without it affecting the streaming video or posting back, that way they have record of how much viewing time there was up until they lost connection.
We used the information from this blog post to accomplish it in our apps. There are code samples that show exactly how to do it. Adjust the
window.setInterval('SaveUserInput()', 10000);
line as needed to change the interval.
You could store the start time in a hidden field when page loads, and then use javascript to post to a webservice at a set interval with the start time.
One option would be to setup an ajax call to talk to the server on an interval to say "I'm still here" - if your ajax call sends a video ID or some other type of session identifier, it can update your database with the appropriate time.
I'd suggest looking into using jQuery for this along with [WebMethods]. It makes it quite simple to accomplish. Here's a nicely written article that talks about how to accomplish it with asp.net: http://dotnetslackers.com/articles/ajax/Using-jQuery-with-ASP-NET.aspx
You say "without a postback" - but does that mean a whole page postback? Otherwise it should be pretty easy to make an AJAX call back to the server from some JavaScript. You could use the JQuery library to easily make the call. Here's a pretty good page discussing how to call a page method from JQuery: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Suggestions to use JQuery or other AJAX library to make ajax call every 5 min are good but if you are new to this, you can use the asp.net ajax extensions Timer object (Toolbox->AJAX Extensions->Timer). its not hard to use, it follows a typical event driven model like other ASP.NET controls

Show some message every day at 08:00 AM with ASP.NET C#

I want to read my database get values, change my old message with new value and then show this newly message. I want to do this reading job at everyday 08:00. How can I know if clock is 08:00 AM? Need to control every second? or what else?
The key thing to note here is that you don't actually need to do this at 8am - you need to do it when the application is in use at 8am or the first time the application is in use after 8am - if, that is, you want to do this solely within your ASP.NET application.
You need to track when the message was last updated.
In ASP.NET in a suitable application startup event, call the update method - which should check to see if the value needs updating - and then set a timer (its been 5 years since I wrote the code to do this last, options will have changed) for the "next" 8am - when the timer fires, call your update method, set the timer again. So, if the app starts it will update if required, if its running the update will happen.
If you have more access to the server then create a windows service to do the update.
There are several options in between these two - create a page or a web service to trigger the update logic within the ASP.NET application and then use an external timer to open the page/call the web service at the scheduled time. The most appropriate solution depends on your hosting enviroment and the other resources available to you.
you could create a windows service and schedule it for the time you require every day.

Handling long page execution times in ASP.NET

I'm working on a web application import program. Currently an admin user can upload a formatted csv file that my page will parse. I'm experiencing an execution duration issue as each line pertains to a file that has to be saved to Scribd, S3, as well as some internal processing.
What would you guys recommend for improving execution time? Since this is an admin only page, I doubt it would get run more than once a week, so my hope is to get it out the door asap.
I've looked some at the Async="true" flag, but I wasn't sure if that was the direction I wanted to go, or if I should look more that a windows server.
Two options come to mind:
Threads: In your code setup a collection of threads, join them and then have each one process a single file. Once all the threads complete you'll be able to return the page. This will increase your turn around time, but could still leave something to be desired on page returns
Queue: Have the user submit the csv file and provide a GUID/Hash/Whatever ID where the admin could then go to the "status" page, input their ID and check the details of their job. This solution will provide a quick feedback to the user and allow them to keep track of the results without having to wait around.
A quick and dirty option might be to set Page.Server.ScriptTimeout to a really high value on that page. (I think it maxes at Int.MaxValue).
Probably advisable to block the submit button after its been clicked, and inform the user that they may want to go make a coffee.
I'd suggest using AJAX to have an internal post back occur that would handle the asynchronous processing. You can periodically poll the state, and prevent your master page from having the "processing" wheel constantly churning on the page for the lengthy process.
I have a web page that takes a long time to process a mailing list so I kick it off in it's own thread. When the process is done, a report can be seen from another link on the result page. I have a runable MailSender class. The ASPX script has a bit in it that looks like this:
// prep the MailSender
MailSender ms = new MailSender(people, Subject, FileName....);
if (SendAsync) {
ThreadStart ts = new ThreadStart(ms.run);
Thread WorkerThread = new Thread(ts);
WorkerThread.Start();
} else {
ms.run();
}
If you want to speed your code up, try to break it into parallelizable pieces if you can and write a class for each piece. You could then kick off a new thread for each bit and monitor the status somewhere so the user can be informed when to come back to the results. You said that each line of your input would generate it's own output file. Sounds like a great candidate for multi-threading. Won't speed things up much if you don't have multi-cores availabe on the server though.
One problem with this whole scheme is that server restarts or application pool recycling will kill your long running process. This can be a problem if you threads are going to run for an hour or two.
As external factors are involved in the processing time, you need to consider if performance improvements would affect "actual" performance, if most of the time is in processing it and sending it to the thirdparty (ie Scribd,S3), then making improvements on your end might not have a huge affect and might increase the complexity for a simple task.
What I would do is have the aspx page only doing what aspx does best; ie handling the user interface part only (ie the upload), so once the upload is complete as far as the user is concerned their part is done. You could implement a progress indicator using AJAX to make it nicer but as its an admin section I wouldnt bother with the niceties,
Then have simple console application sheduled to fire at specific intervals, or a windows service watching a directory (depending on how timecritical the updates are), once the app runs as it is in the back ground and does not require user interaction, time is not a critical factor (ie you dont have a user waiting for context to be returned)..
it will appear to the user that things are very snappy (ie the time it takes to upload the file) and you are keeping needless complexity out of your solution.
I think the simplest solution to what you want is to use asynchronous pages in ASP.NET. Is there any particular reason why you don't want to go that route?
I can think of an alternative, which is to have some background process (like a process triggered by a scheduled task in Windows, or a Windows service) that will look at a queue of waiting jobs (say, from a database table) and process those jobs. This way you will have to upload that CSV somewhere and insert a db record so that the background process will see that CSV and use it when it comes around. But to me it seems like more work, so I'd rather use asynchronous pages :)
Here's a nice tutorial on ASP.NET asynchronous pages

Categories

Resources