how trigger an event on specific time of day .net

Dani AI

Generated

Short summary and context: asked how to run code at a specific time in .NET. and pointed toward OS-level scheduling and services — both valid choices. Below are practical .NET patterns, a small reusable timer example, and production caveats so the job actually runs when you expect.

Pick the right host: if the process must keep running across reboots and you control the machine, a service or OS scheduler is simplest. If the code lives inside an ASP.NET app, do not rely on in-process timers (app pool recycles, idle timeouts, deployments). For reliable scheduling with persistence, use a scheduler library that survives restarts and supports retries.

Example pattern (single-shot timer that computes the next occurrence and reschedules itself). This avoids drift and keeps the work outside the ASP.NET request thread:

private static Timer _timer;

static void ScheduleNextRun(int hour, int minute)
{
    DateTime now = DateTime.Now;
    DateTime next = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
    if (next <= now) next = next.AddDays(1);

    TimeSpan due = next - now;

    _timer?.Dispose();
    _timer = new Timer(_ =>
    {
        try { DoWork(); }
        finally { ScheduleNextRun(hour, minute); }
    }, null, due, Timeout.InfiniteTimeSpan);
}

For production, consider a battle-tested scheduler: Quartz.NET or Hangfire for persistent jobs, retries and dashboards. Also read the .NET timer docs for details: System.Threading.Timer.

Quick tips: always log runs and failures, run under an account with the right permissions, decide explicitly which time zone to use (store schedules in UTC or use TimeZoneInfo), and test behavior across Daylight Saving changes and restarts.

Recommended Answers

All 2 Replies

Look into setting up cron jobs or scheduled tasks on your server. For a web page you can set a scheduled task to run at certain times, calling the web page and thereby running any scripts that are part of the page.
If you are coding a program to run on your computer, look at making a windows service which can be called at set times.

[MS WINDOWS]
If this is a console app or other app that runs unassisted, you can use the windows scheduler.
This can be done from the command-line with the "at" command.

Examine this:

at 05:05 /every:M,T,W,Th,F,S,Su c:\bin\ImportTrunkPlanData\ImportTrunkPlanData.exe

Means at 5:05 every day, run the executable.

If it requires parameters, you will need to put it in a batch file and call the batch file from "at".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.