且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎么可以引发在.NET(每小时或特定的时间间隔)事件每隔一小时?

更新时间:2023-12-02 16:09:46

System.Timers.Timer.如果你想在一天中的特定时间运行,你需要弄清楚它,直到下一次多长时间,并设置为你的时间。

这仅仅是基本的想法。根据如何precise你需要,你可以做得更多。

  INT分钟= DateTime.Now.Minute;
INT调整= 10  - (分10​​%);
timer.Interval =调整* 60 * 1000;
 

I'm working on a little web crawler that will run in the system tray and crawl a web site every hour on the hour.

What is the best way to get .NET to raise an event every hour or some other interval to perform some task. For example I want to run an event every 20 minutes based on the time. The event would be raised at:

00:20
00:40
01:00
01:20
01:40

and so on. The best way I can think of to do this is by creating a loop on a thread, that constantly checks if the time is divisible by a given interval and raises a callback event if the time is reached. I feel like there has got to be a better way.

I'd use a Timer but I'd prefer something that follows a "schedule" that runs on the hour or something along those lines.

Without setting up my application in the windows task scheduler is this possible?

UPDATE:
I'm adding my algorithm for calculating the time interval for a timer. This method takes a "minute" parameter, which is what time the timer should trigger a tick. For example, if the "minute" parameter is 20, then the timer will tick at the intervals in the timetable above.

int CalculateTimerInterval(int minute)
{
    if (minute <= 0)
        minute = 60;
    DateTime now = DateTime.Now;

    DateTime future = now.AddMinutes((minute - (now.Minute % minute))).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);

    TimeSpan interval = future - now;

    return (int)interval.TotalMilliseconds;
}

This code is used as follows:

static System.Windows.Forms.Timer t;
const int CHECK_INTERVAL = 20;


static void Main()
{
    t = new System.Windows.Forms.Timer();
    t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
    t.Tick += new EventHandler(t_Tick);
    t.Start();
}

static void t_Tick(object sender, EventArgs e)
{
    t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
}

System.Timers.Timer. If you want to run at specific times of the day, you will need to figure out how long it is until the next time and set that as your interval.

This is just the basic idea. Depending on how precise you need to be you can do more.

int minutes = DateTime.Now.Minute;
int adjust = 10 - (minutes % 10);
timer.Interval = adjust * 60 * 1000;