简体   繁体   中英

Should I Thread.Sleep for a hours or there are more smarter way?

I have to update some data every 1 hour in a Thread. I put the Method-checker into a new Thread

if ((time_now - last_update) < 3600)
            Thread.Sleep(3600 * 1000);

But I feel like this isn't correct. Maybe there is an elegant and inexpensive way to check for updates every hour without Thread.Sleep in C#?

How about running your pulling method every fixed time:

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromHours(1);

var timer = new System.Threading.Timer((e) =>
{
    YourPullingMethod();
}, null, startTimeSpan, periodTimeSpan);

sleep should not be use. It is unreliable and can not be canceled; it is also blocking

you can do something like the following.

object waitTimeOut = new object();

lock (waitTimeOut) 
{ 
      Monitor.Wait(waitTimeOut, TimeSpan.FromMilliseconds(3600 * 1000)); 
} 

or

 TimeSpan ts = TimeSpan.FromMilliseconds(3600 * 1000);
 t.Wait(ts)

Or with the low frequence you the other comments are good about using a cron job; and would be much more suitable to what you are doing

查看System.Threading.Timer类(或其他计时器,使用最适合您的计时器)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM