如何在c#中设置定时器在特定时间执行 [英] How to set timer to execute at specific time in c#

查看:216
本文介绍了如何在c#中设置定时器在特定时间执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我需要在每天上午 00:01:00 执行计时器......但我不知道如何实现这一点......如果我正在使用系统时间,它可以采用不同的格式..这是我的计时器代码..

I have a requirement where i need to execute timer at 00:01:00 A.M every day...But i am not getting how to achieve this ..If i am taking Systems time,it can be in different format.. Here is my timer code..

static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer(); 

static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Add timer code here

    }
    private static void start_timer()
    {
        timer.Start();
    }

推荐答案

你应该做的是编写你的程序来完成你需要它做的任何事情,然后使用你的操作系统的内置任务调度程序来启动它.那会是最可靠的.例如,Windows 的任务计划程序可以在用户登录之前启动您的应用程序、处理必要时重新启动应用程序、记录错误和发送通知等.

What you should do is write your program that does whatever you need it to do, and then use your OS's built-in task scheduler to fire it off. That'd be the most reliable. Windows's Task Scheduler, for instance, can start your app before the user logs in, handle restarting the app if necessary, log errors and send notifications, etc.

否则,您将必须 24/7 全天候运行您的应用,并让它定期轮询时间.

Otherwise, you'll have to run your app 24/7, and have it poll for the time at regular intervals.

例如,您可以每分钟更改一次间隔:

For instance, you could change the interval every minute:

timer.Interval = 1000 * 60;

在您的 Elapsed 事件中,检查当前时间:

And inside your Elapsed event, check the current time:

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (DateTime.Now.Hour == 1 && DateTime.Now.Minute == 0)
    {
        // do whatever
    }
}

但这确实不可靠.您的应用可能会崩溃.处理 DateTime 可能会很棘手.

But this is really unreliable. Your app may crash. And dealing with DateTime's can be tricky.

这篇关于如何在c#中设置定时器在特定时间执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆