c# - How can I raise an event every day 12:00 AM or specific time interval in c#.NET
Please suggest
Short answer: pick the right host first. If the code runs on a machine you control (desktop app or a Windows Service), schedule a one-shot timer to the next desired occurrence (midnight) and then reschedule each time. If the code runs inside IIS/ASP.NET, do not rely on in-process timers — the app pool can recycle, idle timeout can stop your timer, and deployments will interrupt it. Use an external scheduler (Windows Task Scheduler), a Windows Service, or a persistent job system (Quartz.NET or Hangfire) — or a cloud scheduled job when appropriate.
As suggested, polling every minute is simple but inefficient and fragile. As pointed out, the framework provides Timer classes, but those docs don’t solve hosting reliability. The pattern below shows a robust in-process approach for a trusted host: compute the delay to the next midnight, use a Timer with an infinite period, run the work, then recompute and reschedule (this avoids DST drift and fixed 24-hour assumptions). Protect with an interlock to avoid overlapping runs and wrap work in try/finally to catch exceptions.
using System;
using System.Threading;
class DailyScheduler
{
private Timer _timer;
private int _running;
public void Start()
{
var now = DateTime.Now;
var next = now.Date.AddDays(1); // next local midnight
_timer = new Timer(Callback, null, next - now, Timeout.InfiniteTimeSpan);
}
private void Callback(object state)
{
if (Interlocked.Exchange(ref _running, 1) == 1) return;
try
{
// perform job here (catch exceptions)
}
finally
{
Interlocked.Exchange(ref _running, 0);
var now = DateTime.Now;
var next = now.Date.AddDays(1);
_timer.Change(next - now, Timeout.InfiniteTimeSpan);
}
}
} Notes: use TimeZoneInfo/DateTimeOffset if you need a specific timezone, avoid long-running work inside the timer thread (offload if needed), log failures, and prefer external/persistent schedulers for production web apps.
Jump to Post— superjj 0You can use a timer to check the time every minute.
in the time methode, you make am if function which the DateTime.now.
You can use a timer to check the time every minute.
in the time methode, you make am if function which the DateTime.now.
c# - How can I raise an event every day 12:00 AM or specific time interval in c#.NET
Does nobody read the documentation? I mean, that's a classic RTFM type of question.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.