i have a specific state(business case),i want to check it every period of time,to execute an action..they tell me to write a patch to handle this situation ..
the application i works in is a web application (asp.net开发者_JAVA百科)..
i don't know how to write the patch ,, and i don't know if the patch is the ideal solution in this state or not..
please any suggestions ,, any details explanation for this issue..
thanks in advance.
Firstly, it is quite simple to setup a timer to do this check. Initialise a timer,
int _State;
System.Timers.Timer stateCheckTimer = new System.Timers.Timer();
stateCheckTimer.Interval = 1000; // TODO - set to desired interval (in ms)
stateCheckTimer.AutoReset = true;
stateCheckTimer.Elapsed += stateCheckTimer_Elapsed;
Then just check your state in the stateCheckTimer_Elapsed
function,
void stateCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
The most difficult thing will be accessing the _State, so you'll probably have to put the timer in the same location as it (or have it passed, whatever works). I would suggest an event driven solution though. Make a public event handler on your class that handles the state,
public EventHandler OnStateChanged;
Then, encapsulate the access to your state variable (in this example, _State
) so that you control the setting of it. When it is set, fire off this event. I do this through a property,
public int State
{
get { return _State; }
set
{
_State = value;
if (OnStateChanged != null)
{
OnStateChanged(this, null);
}
}
}
Then, you just need to wire up an event handle to execute your desired action,
OnStateChanged += StateChangeAction;
And in that function execute your desired action,
void StateChangeAction(object sender, EventArgs args)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
(you will have to pass the state in through the EventArgs args but that is pretty simple to do). This way, whenever the state changes you will immediately be able to act upon it (send an email, do whatever it is) rather than having to poll the state every x seconds or minutes. It will use less resources, be more reactive (quicker), and ultimately be neater code! If you are able to do it this way, I would highly recommend it.
this checking is done from the browser or on the server side application ?
if it is done from the client( Browser ) than you can do it with JavaScript See this Post
If you want to do it from the Server Side code than , you can do it with a thread, make thread sleep for some time and when it's wake up than check the state of your object
Is the action to be executed a database one, e.g. update some row in the database? If yes you can create a database job that handles this situation.
What about writing a small simple service that works in the background 24/7. I think its the simplest solution.
精彩评论