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

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

问题描述

我有,我需要在每天上午12点01分00秒来执行计时器的要求......但我没有得到如何实现这个..如果我是把系统时间,它可以在不同的格式。
这里是我的计时器代码..

 静态System.Timers.Timer定时器; 
定时器=新System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24; //一天订省
timer.Elapsed + =新ElapsedEventHandler(timer_Elapsed)的区间;
START_TIMER();

静态无效timer_Elapsed(对象发件人,ElapsedEventArgs E)
{
//添加定时器代码在这里

}
私有静态无效START_TIMER ()
{
timer.Start();
}


解决方案

你应该做的是写你的程序,做任何你需要做的,然后用你的操作系统内置的任务调度火它关闭。这会是最可靠的。窗口的任务计划程序,例如,可以在用户登录时,处理在必要时重新启动应用程序,登录错误并发送通知等之前启动您的应用程序。



否则, '将不得不运行您的应用程序全天候,并将它轮询定期的时间



例如,你可以改变间隔每一分钟:

  timer.Interval = 1000 * 60; 

和您的消逝事件中,检查当前时间:

 静态无效timer_Elapsed(对象发件人,ElapsedEventArgs E)
{
如果(日期时间。 Now.Hour == 1安培;&安培; DateTime.Now.Minute == 0)
{
//做什么
}
}

不过,这实在是不可靠的。您的应用程序可能会崩溃。和处理日期时间的可能会非常棘手。


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();
    }

解决方案

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.

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;

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
    }
}

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

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

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