Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling running a method at a certain time.

This is a rather simple issue, but every time I try to find the answer it keeps showing things about Windows Scheduled Tasks, and this is not what this is.

Say my program is basically this:

void StartDoingThings()
{
   //At Specific System.DateTime
   DoSomething()

   //At another specific System.Datetime
   DoSomethingElse()
}

What do I put instead of those comments to cause those methods to run at separate datetimes.

I could use Thread.Sleep() or even System.Threading.Timers and calculate intervals based off of (DateTimeOfEvent - DateTime.Now), but is there simply something to say (assuming the program is still running): At 9:30:00 AM on 11/30/2012, perform the method DoAnotherThing() ?

like image 730
Xantham Avatar asked Nov 29 '12 20:11

Xantham


People also ask

How do I schedule a task at a specific time?

One of the methods the Timer class is void scheduleAtFixedRate(TimerTask task, Date firstTime, long period). This method schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

How do you schedule a method in Java?

One of the methods in the Timer class is the void schedule(Timertask task, Date time) method. This method schedules the specified task for execution at the specified time. If the time is in the past, it schedules the task for immediate execution.

How do you execute a method in ASP NET MVC for every 24 hours?

You can create an external trigger that calls into your MVC action method every 24 hours. So you are executing your code every 24 hours. There are multiple ways and services to do that, i have used different services. Or you can create your own if you do not want to use third party.


1 Answers

If you want to "schedule" a method to do something at a predetermined time, there are a number of ways to do that. I would not use Thread.Sleep() because that would tie up a thread doing nothing, which is a waste of resources.

A common practice is to use a polling method that wakes up on a regularly timed schedule (let's say once a minute) and review a shared list of tasks to perform. System.Timer can be used for the polling method:

aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

The OnTimedEvent method can contain code that maintains a collection of "tasks" to perform. When a task's time comes up, the next run of the Timer will cause it to execute.

like image 91
Dave Swersky Avatar answered Nov 01 '22 23:11

Dave Swersky