How to Call a Method Daily, At Specific Time, in C#

How to call a method daily, at specific time, in C#?

  • Create a console app that does what you're looking for
  • Use the Windows "Scheduled Tasks" functionality to have that console app executed at the time you need it to run

That's really all you need!

Update: if you want to do this inside your app, you have several options:

  • in a Windows Forms app, you could tap into the Application.Idle event and check to see whether you've reached the time in the day to call your method. This method is only called when your app isn't busy with other stuff. A quick check to see if your target time has been reached shouldn't put too much stress on your app, I think...
  • in a ASP.NET web app, there are methods to "simulate" sending out scheduled events - check out this CodeProject article
  • and of course, you can also just simply "roll your own" in any .NET app - check out this CodeProject article for a sample implementation

Update #2: if you want to check every 60 minutes, you could create a timer that wakes up every 60 minutes and if the time is up, it calls the method.

Something like this:

using System.Timers;

const double interval60Minutes = 60 * 60 * 1000; // milliseconds to one hour

Timer checkForTime = new Timer(interval60Minutes);
checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
checkForTime.Enabled = true;

and then in your event handler:

void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
if (timeIsReady())
{
SendEmail();
}
}

execute some code at a certain time daily

If you simply want to run something at the same time every day, you can use the built in task scheduler.

You can setup a daily schedule that will execute your application at the same time every day.

Otherwise, in your application you will need to setup a timer and check in the tick event if the current time is 3pm and only call your method at that point.

I would have suggested a windows service, but as you stated that you only need the method to run if the application is already running, this is not needed.

Start function at specific time in C#

You can do something like this. Here we are using a timer to do the scheduling part of the program. You can use this in a windows service to make your program more effective. But if that's not what you want, you can still use this in your winforms app.

public class EmailScheduler : IDisposable
{
private readonly Timer clock;

public EmailScheduler()
{
clock = new Timer();
clock.Interval = 1000; // runs every second just like a normal clock
}

public void Start()
{
clock.Elapsed += Clock_Elapsed;
this.clock.Start();
}

public void Stop()
{
clock.Elapsed -= Clock_Elapsed;
this.clock.Stop();
}

private void Clock_Elapsed(object sender, ElapsedEventArgs e)
{
var now = DateTime.Now;

// Here we check 9:00.000 to 9:00.999 AM. Because clock runs every 1000ms, it should run the schedule
if (now.DayOfWeek == DayOfWeek.Monday &&
(now.TimeOfDay >= new TimeSpan(0, 9, 0, 0, 0) && now.TimeOfDay <= new TimeSpan(0, 9, 0, 0, 999)))
{
// 9 AM schedule
}

if(now.Date.Day == 1 &&
(now.TimeOfDay >= new TimeSpan(0, 9, 0, 0, 0) && now.TimeOfDay <= new TimeSpan(0, 9, 0, 0, 999)))
{
// 1 day of the month at 9AM
}
}

public void Dispose()
{
if (this.clock != null)
{
this.clock.Dispose();
}
}
}

To start scheduler you may do something like this in your form.

   private EmailScheduler scheduler;
public void FormLoad()
{
scheduler = new EmailScheduler();
scheduler.Start();
}

public void FormUnload()
{
scheduler.Stop();
scheduler.Dispose();
}

Code for executing method every day at specific time C# (Windows Service) failed

GC will collect your timer since you don't have any references to it after OnStart method.

You're just having it as a local variable. I hope you know local variables are eligible for garbage collection once JIT says that they are no longer used in code.

Fix: Just store the timer in a instance variabe, you're done.

private System.Threading.Timer my5AmTimer = null;

protected override void OnStart(string[] args)
{
//All other code..

this.my5AmTimer = new System.Threading.Timer(callback, null, next5am - DateTime.Now, TimeSpan.FromHours(24));
}

Run C# code at specific time

in the question set as possible duplicate: C# Execute function at specific time people suggest to use either Quartz.NET or windows Task Scheduler.

Both options could eventually serve the purpose but I believe, as I suggested already few times in similar previous questions, Windows Task Scheduler is better because you no code anything for it and let Windows do the scheduling for you and you focus only on the real business case of your application, which is what Windows cannot do for you, then rely on existing technologies to glue things together and don't have to debug or reinvent what has been done and is available for you anyway.



Related Topics



Leave a reply



Submit