How can i run a method in silverlight once a month? - c#

I have a program that displays some information in the form of a chart. The information updates every month and so i need to retrieve the information once a month.
I thought about having a thread that sleeps for a months time but, i don't know if that is doable. Can someone suggest a better way to do this?
thanks!

You can store the last accessed date in a file/table and then poll the file/table each day when the program starts. If it exceeds 1 month(30/31 days) then re-get your data.
Use the DateTime class in .NET to help you with it. Also use DateTime.Subtract() between two dates.

I'm wondering what you're trying to do here. It sounds... odd.
So, where is the info coming from? A database? If so, can you just calculate the month's values when pulling the data normally? Or you could have a job running in SQL Agent that updates a table once a month with the calculated values.
Really with windows you could set up a scheduled task with a similar concept. It runs once a month and pulls down the new data.
But basically a little more info about what you're trying to do might help us give you better answers..

I have seen implementations where on startup a thread is started and calculates the time until the next read time. Within the thread it waits for a shutdown event to be signalled (which is fired by the app), the timeout value is the previously calculated time. Once wait is complete, if it wasn't due to shutdown event, then data is read.
However, the more common implementation that I have seen is to use scheduled tasks to load the data to the app. Although this will take longer to implement than threaded version, it should provide a more robust solution.

Related

Scheduling methods to run in ASP.NET

Explanation:
I am developing a simple car business system and I have to implement the following feature:
A very special car model is delivered to a shop. There are a lot of people on waiting list exactly for this model.
When the car arrives the first client receives the right to buy it, he / she has 24 hours to use this opportunity.
I have a special state in the DB that determines if the user is: on waiting list (I have the exact position, as well) or can use opportunity to buy the car. Whenever the car arrives, I run a method that changes the state of the first client on waiting list. And here comes the problem:
Problem:
The client can use his opportunity, during the 24 hours period. But I have to check at the end, if he/she has bought the car. For this reason, I have to schedule a method to run in 24 hours.
Possible solution:
I am thinking about two things. First is using a job scheduler like Hangfire. The problem is that since I do not have any other jobs in my app, I do not want to include a whole package for such a small thing. Second is using making the checking method asynchronous and making the thread sleep for 24 hours before proceeding (I do not feel comfortable in working with threads and this is just an idea). I got the idea from this article. Keep in mind that more than one car can arrive in more than one shop. Does it mean that I should use many threads and how it is going to affect the performance of the system?
Question:
Which of the two solutions is better?
Is there another possibility that you can suggest in this particular case?
I agree. Importing a package for only one job if you aren't going to use it for many jobs is a little bit of overkill.
If you are running SQL server, I'd recommend writing a .NET console application to run on a schedule using the SQL Server Agent. (see image) If you have stored procedures that need to run, you also have the option to run them directly from the SQL job if for some reason you don't want to run them from your .NET application.
Since it sounds like you need this to run on a data driven schedule, you may consider adding a trigger to look for a new record in your database whenever that "special" car is inserted into the database. MSDN SQL Job using Trigger
I've done something similar to this where every morning, an hour prior to business hours starting, I run a .NET executable that checks the latest record in table A and compares it to a value in table B and determines if the record in table A needs to be updated.
I also use SQL Server to run jobs that send emails on a schedule based on data that has been added or modified in a database.
There are advantages to using SQL server to running your jobs as there are many options available to notify you of events, retry running failed jobs, logging and job history. You can specify any type of schedule from repeating frequently to only running once a week.

Recurring event Reminder using asp.net and Ms SQL

I have been asked to add a feature to some software I have written which needs to send reminder emails.
The reminders can have a recurrence; for example, it might recur every 3 days or every 2 weeks. The reminders also have a start and end date. I have created an SQL table with these fields:
event_id
event_name
event_Description
event_startDate
event_endDate
RecurrenceType (e.g. Daily, Weekly, Monthly,Yearly)
Intarval
event_ActiveFlag
I now need to write a stored procedure that will run every time and send the reminders. I have no problem with sending via a C# console application; the trouble I am having is that I cannot figure out how to get the recurrences for the current day.
No matter what, you cannot get around needing to perform a computation to determine the list of recurrence dates for a given event. By "computation" I mean something like the following pseudocode:
foreach(event in activeEvents)
{
while(recurrenceDate <= currentDate && recurrenceDate <= event.EndDate)
{
event.RecurrenceDates.Add(recurrenceDate);
recurrenceDate.AddDays(event.IntervalLengthInDays);
}
}
I highly recommend using Douglas Day's excellent .NET iCal library (be sure to read the license terms to ensure you are permitted to use this in your app, though they are quite permissive) to calculate recurrence dates for you, because despite appearing straightforward, it's actually very difficult to correctly handle all the corner cases.
This will give you a list of dates that the event occurs on, up to the current date. There are two questions: when and where should you perform this calculation?
As for where, I recommend in the C# app, since you've already stated you have such a component involved. It is absolutely possible to do this in a performant, set-based way in your SQL database; however, the obvious, intuitive way to code this is using loops. C# is great at loops; SQL is not. And doing it the obvious way will make it much easier to debug and maintain when you (or someone else) looks at it six months down the line.
Regarding when, there are two possibilities:
Option 1: On demand: do it as part of the job that sends your daily reminder blast.
Fetch the data for all active events
Compute recurrence lists for them
Examine the last recurrent event (this will be the one closest to the current date) to determine if that event should be sent out as a reminder
Send eligible reminders
Option 2: Once: do it when the event is created and entered in the system.
When an event is created, calculate all recurrence dates through its end date
Store these dates in a table in the DB (event_id FK, event_date)
Your reminder job fetches a list of eligible events (both active and has the appropriate date) from the precomputed table
Send eligible reminders
Which option is better? My money is on #1. Why?
With option 1, if I realize I accidentally entered "daily" instead of "weekly" for my recurrence period, changing the event is much easier, because I don't have recompute and re-store all the recurrence data. This is the reason to calculate recurrence on demand, and should trump all but the most dire of performance related concerns (most of which could likely be fixed by throwing more hardware at the problem, or by better load balancing).
Option 2 is degenerate in the case of events without a defined end date. This is manageable by, say, calculating X years into the future, but what happens X years later?
A daily reminder job probably runs overnight, and so doesn't need to execute super fast. This means cutting down on its execution time isn't a priority. And the recurrence calculation time is probably going to be negligible anyway; I expect the bottleneck to be the actual email sending. However, if you have a lot of active, old events to consider (by "a lot", I mean billions) and/or your app server is grinding to a halt under load, this may become important.
Option 1 saves DB work. I don't mean storage space (although it does use less); that shouldn't matter unless you have a lot (many trillions) of events. I mean that it's less "chatter" back and forth between your app server and the DB, so there's less chance for a dropped connection, concurrency collision, etc. Please note this is incredibly trivial and really doesn't matter either way, unless your production environment has major problems.

Framework to handle recurring tasks

We implemented a windows service that has a couple of timers in it. Over time the logic for the timers got more and more complicated. Its time to refactor our solution and one possible way would be to use a well documented framework that handles our requirements.
There are rules like:
start timer A each day at 9am
start timer B each 2min
if timer A is started dont start any other timer
timer C and D are not allowed to run at the same time
I looked at Quartz.net because it had the first 2 requirements of our list, but it doesnt handle any concurrency rules.
Is there any framework I could have a look at?
I had similar requirements: essentially what you need is a state machine that can be easily serialized to disk or a database, some way to specify the state machine easily using hierarchical states, some way to easily specify temporal events (After, Every, At) and some way to easily know when to load the state machine back into memory to advance state based on the current time.
In the end I wrote my own state machine as I didn't find one that met my requirements, in particular the temporal events and the serialization requirements. You can get the source code in a Nuget Package. Blog entry here. Feedback welcome.

Timer start at 3am every day

I found this code. But i would like to know if is possible that instead of intervat program will start every day at 3 am?
edit: code
http://www.codeguru.com/forum/showthread.php?t=483012
thx
You can accomplish this using Task Scheduler, no need for controlling this programmatically. Unless its a windows service you are implementing, in that case you would need to check the time on the hour and do your processing respectively (and that's not taking into account if your using different timezones)
I'm afraid that if you are not using the task scheduler your service will have to run continuously. You need to change the example you link to as follows:
The example code you link to uses an interval of 2 seconds. You may shorten the length of the interval to 1 second or even less.
The implementation of the OnTick(...) method should check if it's 3AM. If this is the case, do whatever it is you need to do.

Good way of firing an event at a particular time of day?

I have an app that needs to fire off a couple of events at certain times during the day - the times are all defined by the users. I can think of a couple of ways of doing it but none of them sit too well. The timing doesn't have to be of a particularly high resolution - a minute or so each way is fine.
My ideas :
When the app starts up read all the times and start timers off that will Tick at the appropriate time
Start a timer off that'll check every minute or so for 'current events'
tia for any better solutions.
Store/index the events sorted by when they next need attention. This could be in memory or not according to how many there are, how often you make changes, etc. If all of your events fire once a day, this list is basically a circular buffer which only changes when users change their events.
Start a timer which will 'tick' at the time of the event at the head of the list. Round up to the next minute if you like.
When the timer fires, process all events which are now in the past [edit - and which haven't already been processed], re-insert them into the list if necessary (i.e. if you don't have the "circular buffer" optimisation), and set a new timer.
Obviously, when you change the set of events, or change the time for an existing event, then you may need to reset the timer to make it fire earlier. There's usually no point resetting it to fire later - you may as well just let it go off and do nothing. And if you put an upper limit of one minute on how long the timer can run (or just have a 1 minute recurring timer), then you can get within 1-minute accuracy without ever resetting. This is basically your option 2.
Arguably you should use an existing framework rather than rolling your own, but I don't know C# so I have no idea what's available. I'm generally a bit wary of the idea of setting squillions of timers, because some environments don't support that (or don't support it well). Hence this scheme, which requires only one. I don't know whether C# has any problems in that respect, but this scheme can easily be arranged to use O(1) RAM if necessary, which can't be beat.
Have a look at Quartz.Net. It is a scheduler framework (originally for Java).
This sounds like a classic case for a Windows Service. I think there is a Windows Service project type in VS2005/2008. The service coupled with a simple database and a front-end application to allow users to set the trigger times would be all you need.
If it won't change very often, Scheduled Tasks is also an option.
I've written a few programs along these lines.
I suggest #2. All you need to to is keep a list of times that events are "due" at, and every X amount of time (depending on your resolution) check your list for "now" events. You can pick up some optimization if you can guarantee the list is sorted, and that each event on the list is due exactly once. Otherwise, if you have recurring events, you have to make sure you cover your window. What I mean is, if you have an event that is due at 11:30 am, and you're checking every seconds, then it's possible that you could check at 11:29:59, and then not again until 11:31:01, due to the inprecision of the CPU time-slices. So you'll need to be sure that one of those checks (11:29 or 11:31) still picks up the 11:30 hit, and that ONLY one of them does (i.e., you don't run at both 11:29 and 11:31).
The advantage this approach has over checking only on times you know to be on your list is that allows your list to be modified by 3rd parties without your knowledge, and your event handler will continue to 'just work'.
The simplest way would likely be to use Windows scheduler.
Otherwise you need to use one of the Timer classes, calculating how long until the first event. This approach, unlike the scheduler, allows new events to be found by the running process (and, possibly, resetting the timer).
The problem with #1 is that the number of milliseconds before an event may be too large to store in the Timer's interval, and as the number of events increase, your number of timers could get unweildly.
I dont see anything wrong with #2, but I would opt for a background worker or a thread.

Categories

Resources