Home > Backend Development > C++ > How to Schedule a Daily Task in a C# Windows Service?

How to Schedule a Daily Task in a C# Windows Service?

Susan Sarandon
Release: 2025-01-10 10:27:40
Original
885 people have browsed it

How to Schedule a Daily Task in a C# Windows Service?

Scheduling tasks in C# Windows Service

For situations where a task needs to be executed every midnight in a Windows service written in C#, it is recommended to use the task scheduler instead of relying on Thread.Sleep() and time-based checks.

An effective approach is to implement a timer in the service. The timer should fire periodically, say every 10 minutes, and verify if the date has changed since the last execution. If a new date is detected, the timer is paused while the cleanup process is performed, ensuring that it is only performed once per day.

<code class="language-csharp">private Timer _timer;
private DateTime _lastRun = DateTime.Now.AddDays(-1);

protected override void OnStart(string[] args)
{
    _timer = new Timer(10 * 60 * 1000); // 每10分钟
    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
    _timer.Start();
    //...
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    // 忽略时间,只比较日期
    if (_lastRun.Date < DateTime.Now.Date)
    {
        // 在运行清理任务时停止计时器
        _timer.Stop();
        //
        // 执行清理任务
        //
        _lastRun = DateTime.Now;
        _timer.Start();
    }
}</code>
Copy after login

The above is the detailed content of How to Schedule a Daily Task in a C# Windows Service?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template